How to read a file into string in java?

Viewed 96586

I have read a file into a String. The file contains various names, one name per line. Now the problem is that I want those names in a String array.

For that I have written the following code:

String [] names = fileString.split("\n"); // fileString is the string representation of the file

But I am not getting the desired results and the array obtained after splitting the string is of length 1. It means that the "fileString" doesn't have "\n" character but the file has this "\n" character.

So How to get around this problem?

14 Answers

Fixed Version of @Anoyz's answer:

import java.io.FileInputStream;
import java.io.File;

public class App {
public static void main(String[] args) throws Exception {

    File f = new File("file.txt");
    long fileSize = f.length();

    String file = "test.txt";

    FileInputStream is = new FileInputStream("file.txt");
    byte[] b = new byte[(int) f.length()];  
    is.read(b, 0, (int) f.length());
    String contents = new String(b);
}
}
Related