25 Sept 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:

  1. Anonymous9:52 am

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

    ReplyDelete
  2. Anonymous5:06 pm

    Yes, it is *really* not rocket science

    ReplyDelete
  3. Anonymous1:10 pm

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

    ReplyDelete
  4. Anonymous10:46 am

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

    ReplyDelete

Note: only a member of this blog may post a comment.