25 Sep 2007

Reading lines

I know this sound stupid but even if I've been using Java since 2001, reading a file "line by line" has always been a painful experience because java.io just sucks!
Ok may be it's wonderful piece of Object Oriented design but still "simple things are not simple" :(

With apache commons io to the rescue things become "more" simple:
InputStream input = getClass().getClassLoader().
getResourceAsStream("my/package/file.txt");
List lines = IOUtils.readLines(input, "UTF-8");

or
File file = new File("/commons/io/project.properties");
List lines = FileUtils.readLines(file, "UTF-8");

Still not simple enough but much better ;)

4 comments:

Anonymous said...

yet, it's not rocket science:
http://www.exampledepot.com/egs/java.io/ReadLinesFromFile.html

Anonymous said...

Yes, it is *really* not rocket science

Anonymous said...

Well, it gets trickier if you don't want to use deprecated code like the given example does... :(

Anonymous said...

I didn't see any deprecated code in the example ;-)