(RLUJ)

Reading Lines Using Java

August 21, 2008 @ 20:41:29

Every year or so, for whatever reason, I end-up trying to read text files line by line using Java. I always start out thinking regular expressions, and it always starts to look unnecessarily convoluted.

Three or four years ago I came across BufferedReader and, whatdya know, its got the function readLine. Of course, each time I start anew, I forget the lessons I’ve previously learned. Then, when the code’s starting to look rough, I remember “Oh yeah, there’s a really easy way to do this.” So I find the old code and voilĂ .

I realize this is simple stuff. It’s just one of those things that’s worth putting out there for the occasional search result that might help someone out .

/* Note that I've left out exception handling. */
 
ArrayList<String> lines = new ArrayList<String>();
File file = new File("C:\path\to\file.txt");
 
BufferedReader reader = new BufferedReader(new FileReader(file));
 
String line;
while((line = bufferedReader.readLine()) != null)
     lines.add(line);			
 
bufferedReader.close();

2 Comments

Follow Comments