Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.java.programmer > #25827

Re: Shortest way to read all lines (one by one) from a text file?

From Lew <noone@lewscanon.com>
Newsgroups comp.lang.java.programmer
Subject Re: Shortest way to read all lines (one by one) from a text file?
Date 2011-02-11 07:51 -0500
Organization albasani.net
Message-ID <ij3bb4$eal$1@news.albasani.net> (permalink)
References <4d54f158$0$6975$9b4e6d93@newsspool4.arcor-online.net> <c_CdnSN0wqBIZ8nQnZ2dnUVZ_jqdnZ2d@posted.palinacquisition>

Show all headers | View raw


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?

-- 
Lew
Ceci n'est pas une fenĂȘtre.
.___________.
|###] | [###|
|##/  | *\##|
|#/ * |   \#|
|#----|----#|
||    |  * ||
|o *  |    o|
|_____|_____|
|===========|

Back to comp.lang.java.programmer | Previous | NextNext in thread | Find similar


Thread

Re: Shortest way to read all lines (one by one) from a text file? Lew <noone@lewscanon.com> - 2011-02-11 07:51 -0500
  Re: Shortest way to read all lines (one by one) from a text file? Real Gagnon <realgag+usenet@geocities.com> - 2011-02-11 22:34 +0000

csiph-web