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

  • Follow


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?
           
Robin

0
Reply rob 2/11/2011 8:20:40 AM

On 2/11/11 4:20 PM, 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?

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.

Pete
0
Reply Peter 2/11/2011 9:01:08 AM


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|
|_____|_____|
|===========|
0
Reply Lew 2/11/2011 12:51:27 PM

rob@wenger.net (Robin Wenger) writes:

> 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?
>            

http://commons.apache.org/io/api-1.4/org/apache/commons/io/FileUtils.html#readLines(java.io.File)

For a more memory-efficient approach, see LineIterator in the same package.

-- 
Jim Janney

0
Reply Jim 2/11/2011 3:23:15 PM

On 11.2.2011 10:20, 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?
>            
> Robin
> 

public interface MySimpleUtilities
{
    public static String[] readWholeFile(String filename)
       throws IOException ;
}

Why is it so hard to implement own tools for ones liking?

-- 

Your temporary financial embarrassment will be relieved in a surprising
manner.
0
Reply Donkey 2/11/2011 4:03:40 PM

Lew <noone@lewscanon.com> wrote in news:ij3bb4$eal$1@news.albasani.net:

> The Scanner class also provides compact ways to do this, although it's
> field oriented rather than line oriented. 

True but it's possible to use the EOF as the delimiter

   Scanner scanner = 
      new Scanner(new File("c:/temp/text.txt")).useDelimiter("\\Z");
    String contents = scanner.next();

BYe.


-- 
Real Gagnon  from  Quebec, Canada
* Java, Javascript, VBScript or PowerBuilder snippets
* http://rgagnon.com/howto.html
* http://rgagnon.com/bigindex.html
0
Reply Real 2/11/2011 10:34:53 PM

In article <4d54f158$0$6975$9b4e6d93@newsspool4.arcor-online.net>,
 rob@wenger.net (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?
>            
> Robin

The problem with your one-liner example is that it provides 
functionality good for scripting but bad for general purpose 
programming.  Java is a general purpose language so it needs more 
descriptive coding.

final BufferedReader in= new BufferedReader(new FileReader("foo.txt"));
try
{
   String line;
   while ((line= in.readLine()) != null)
      System.out.println(line);
}
finally
{
   in.close();
}

Of course you can write your own Iterable that a for-each style loop 
will accept.  It's late and my mind is foggy so debugging and preventing 
file descriptor leaks is up to you :)

for (String s : new LineReader(new File ("foo.txt")))
         System.out.println(s);


class LineReader implements Iterable<String> 
{
  final File m_file;
  LineReader (final File f)
  {
    m_file= f;
  }
  @Override
  public Iterator<String> iterator()
  {
    try
    {
      final BufferedReader in=
        new BufferedReader(new FileReader(m_file));
      return new Iterator<String>()
      {
        String line= null;
        @Override public boolean hasNext()
        {
          try
          {
            if (line == null)
              line= in.readLine();
            if (line == null)
            {
              in.close();
              return false;
            }
            return true;
          }
          catch (IOException e)
          {
            throw new RuntimeException(e);
          }
        }

        @Override public String next()
        {
          if (!hasNext())
            throw new NoSuchElementException();
          final String rv= line;
          line= null;
          return rv;
        }

        @Override
        public void remove()
        {
          throw new UnsupportedOperationException();
        }
      };
    }
    catch (IOException e)
    {
      throw new RuntimeException(e);
    }
  }
}
-- 
I will not see posts or email from Google because I must filter them as spam
0
Reply Kevin 2/12/2011 6:15:32 AM

Kevin McMurtrie wrote:
> The problem with your one-liner example is that it provides
> functionality good for scripting but bad for general purpose
> programming.  Java is a general purpose language so it needs more
> descriptive coding.
>
> final BufferedReader in= new BufferedReader(new FileReader("foo.txt"));
> try
> {
>     String line;
>     while ((line= in.readLine()) != null)
>        System.out.println(line);
> }
> finally
> {
>     in.close();
> }

A 'for' loop would do that 'try' block in one line, without writing a custom 
'Iterator'.  Why imply that it can't?

  try
  {
  for( String line; (line=in.readLine()) != null; System.out.println(line));
  }

Why you'd want to is another question.

-- 
Lew
Ceci n'est pas une fenêtre.
..___________.
|###] | [###|
|##/  | *\##|
|#/ * |   \#|
|#----|----#|
||    |  * ||
|o *  |    o|
|_____|_____|
|===========|
0
Reply Lew 2/12/2011 2:52:04 PM

On Fri, 11 Feb 2011 22:34:53 +0000, Real Gagnon wrote:

> Lew <noone@lewscanon.com> wrote in news:ij3bb4$eal$1@news.albasani.net:
> 
>> The Scanner class also provides compact ways to do this, although it's
>> field oriented rather than line oriented.
> 
> True but it's possible to use the EOF as the delimiter
> 
>    Scanner scanner =
>       new Scanner(new File("c:/temp/text.txt")).useDelimiter("\\Z");
>     String contents = scanner.next();
>
That assumes the code will only ever be used on a DOS/Windows box and 
that the file writer appends Ctrl-Z to the file: DOS/Windows is the only 
OS I know where some, but not all, text handling programs do that. 

The OP didn't mention either case as characteristic of his input file.


-- 
martin@   | Martin Gregorie
gregorie. | Essex, UK
org       |
0
Reply Martin 2/12/2011 6:08:01 PM

On 11 Feb 2011 08:20:40 GMT, rob@wenger.net (Robin Wenger) wrote,
quoted or indirectly quoted someone who said :

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

see http://mindprod.com/jgloss/fileio.html

It will generate you code for hundreds of scenarios.  Reading the line
is pretty terse. Getting the file open is a bit of a song and dance if
you want to be explicit about the encoding.

-- 
Roedy Green Canadian Mind Products
http://mindprod.com
Refactor early. If you procrastinate, you will have
even more code to adjust based on the faulty design.
..

0
Reply see_website (4858) 2/13/2011 5:41:41 AM

Martin Gregorie <martin@address-in-sig.invalid> writes:

> On Fri, 11 Feb 2011 22:34:53 +0000, Real Gagnon wrote:
>
>> Lew <noone@lewscanon.com> wrote in news:ij3bb4$eal$1@news.albasani.net:
>> 
>>> The Scanner class also provides compact ways to do this, although it's
>>> field oriented rather than line oriented.
>> 
>> True but it's possible to use the EOF as the delimiter
>> 
>>    Scanner scanner =
>>       new Scanner(new File("c:/temp/text.txt")).useDelimiter("\\Z");
>>     String contents = scanner.next();
>>
> That assumes the code will only ever be used on a DOS/Windows box and 
> that the file writer appends Ctrl-Z to the file: DOS/Windows is the only 
> OS I know where some, but not all, text handling programs do that. 
>
> The OP didn't mention either case as characteristic of his input file.

That was my first thought, too.  But if you check the docs for
java.util.regex.Pattern, backslash Z matches the end of the input.  Look
under Boundary Matchers.

-- 
Jim Janney
0
Reply jjanney (252) 2/14/2011 8:31:34 AM

On Fri, 11 Feb 2011 07:51:27 -0500, Lew wrote:

> 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?

How about we use a real language:

(for [x (line-seq (reader-on file))]
  (do-something-with x))

;)
0
Reply zjkg3d9gj56 (26) 2/14/2011 11:17:38 AM

On 02/14/2011 03:31 AM, Jim Janney wrote:
> Martin Gregorie<martin@address-in-sig.invalid>  writes:
>
>> On Fri, 11 Feb 2011 22:34:53 +0000, Real Gagnon wrote:
>>
>>> Lew<noone@lewscanon.com>  wrote in news:ij3bb4$eal$1@news.albasani.net:
>>>
>>>> The Scanner class also provides compact ways to do this, although it's
>>>> field oriented rather than line oriented.
>>>
>>> True but it's possible to use the EOF as the delimiter
>>>
>>>     Scanner scanner =
>>>        new Scanner(new File("c:/temp/text.txt")).useDelimiter("\\Z");
>>>      String contents = scanner.next();
>>>
>> That assumes the code will only ever be used on a DOS/Windows box and
>> that the file writer appends Ctrl-Z to the file: DOS/Windows is the only
>> OS I know where some, but not all, text handling programs do that.
>>
>> The OP didn't mention either case as characteristic of his input file.
>
> That was my first thought, too.  But if you check the docs for
> java.util.regex.Pattern, backslash Z matches the end of the input.  Look
> under Boundary Matchers.

Yeah, no one suggested to use Control-Z.  DOS and Windows don't use backslash 
Z to indicate end of file.

-- 
Lew
Honi soit qui mal y pense.
0
Reply noone7 (3512) 2/14/2011 12:08:07 PM

12 Replies
427 Views

(page loaded in 0.195 seconds)

Similiar Articles:


















7/25/2012 1:27:36 PM


Reply: