Robin Wenger wrote:
Ok, I know in general a way to read text lines ony-by-one from a file
into a string variable.
But I miss somehow a short one-liner like:
foreach(String currentline : file("D:\test\myfile.txt")) { ....
}
Is there something like this in Java? What would be the shortest way
otherwise?
Peter Duniho wrote:
Well, a BufferedReader is a good way to read a line at a time. It would
be trivial to wrap that in an Iterable implementation so that you could
use the syntax above.
The Scanner class also provides compact ways to do this, although it's
field oriented rather than line oriented. But I have to ask, for what
purpose do you want a one-liner? Is this just intellectual curiosity?
The normal loop, ignoring exceptions for a heartbeat, is like:
BufferedReader reader = ...;
for ( String line; (line = reader.readLine()) != null; ) {
// do something with line
}
How much more compact do you want?