Java – How to Read a File into String

java

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?

Best Answer

What about using Apache Commons (Commons IO and Commons Lang)?

String[] lines = StringUtils.split(FileUtils.readFileToString(new File("...")), '\n');
Related Question