Tuesday, June 24, 2008

Java One Liner - Reading a Text File at Once

Java is not meant or known for any one-liners, but who said we can't try? There you go:
String contents = new Scanner(new File("filepath")).findWithinHorizon(Pattern.compile(".*", Pattern.DOTALL), 0);

Cool, eh?

Hmm, may be not. Of course, you still have to deal with the checked exceptions + 3 import statements, etc. The so called one-liner by me has 113 characters (could be more or could be less if you consider the file path's length). I'm not sure if I would consider anything more than 80 chars as "one-liner" but hey, this is Java and this is as close as you can get.

Just for fun. Do you have anything better than this in Java? How about in Java 1.4? Now, don't write a separate method, call it, and say it's a one-liner for Perl sakes!