(RLUJ)
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
Uh, as a sign I spend too much time in the web world, the thought of reading data from a text file makes my lip curl. I like accessing my data the web way: databases and user input.
Files are so messy.
In the enterprise world, you would be amazed/concerned how often you need to pull data from legacy systems that don’t allow database access, aren’t wrapped in a convenient web service and for various other reasons end up giving you a CSV file as your only data extract mechanism.
I end up using BufferedReader a LOT for integration reasons.