Thursday, March 19, 2009

How do I read a text file line by line into a List?

The readLine() method of java.io.BufferedReader class reads the next line from a text file. When it reaches the end of the file it will return null.


List lines = new ArrayList();
BufferedReader in = new BufferedReader(new FileReader(filename));
String line = null;
while (null!=(line=in.readLine()))
{
lines.add(line);
}
in.close();

// lines will now contain the contents of the file

No comments: