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

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

Post by rob » Sat, 12 Feb 2011 17:20:40


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
 
 
 

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

Post by Peter Duni » Sat, 12 Feb 2011 18:01:08


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

 
 
 

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

Post by Lew » Sat, 12 Feb 2011 21:51:27


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 fentre.
.___________.
|###] | [###|
|##/ | *\##|
|#/ * | \#|
|#----|----#|
|| | * ||
|o * | o|
|_____|_____|
|===========|
 
 
 

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

Post by Jim Janne » Sun, 13 Feb 2011 00:23:15


XXXX@XXXXX.COM (Robin Wenger) writes:


http://www.yqcomputer.com/ #readLines(java.io.File)

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

--
Jim Janney
 
 
 

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

Post by Donkey Hot » Sun, 13 Feb 2011 01:03:40


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.
 
 
 

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

Post by Real Gagno » Sun, 13 Feb 2011 07:34:53


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://www.yqcomputer.com/
* http://www.yqcomputer.com/
 
 
 

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

Post by Kevin McMu » Sun, 13 Feb 2011 15:15:32

In article <4d54f158$0$6975$ XXXX@XXXXX.COM >,



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
 
 
 

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

Post by Lew » Sun, 13 Feb 2011 23:52:48


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 fentre.
.___________.
|###] | [###|
|##/ | *\##|
|#/ * | \#|
|#----|----#|
|| | * ||
|o * | o|
|_____|_____|
|===========|
 
 
 

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

Post by Martin Gre » Mon, 14 Feb 2011 03:08:01


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 |
 
 
 

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

Post by Roedy Gree » Mon, 14 Feb 2011 14:41:41

On 11 Feb 2011 08:20:40 GMT, XXXX@XXXXX.COM (Robin Wenger) wrote,
quoted or indirectly quoted someone who said :


see http://www.yqcomputer.com/

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://www.yqcomputer.com/
Refactor early. If you procrastinate, you will have
even more code to adjust based on the faulty design.
.
 
 
 

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

Post by Jim Janne » Tue, 15 Feb 2011 17:31:34

Martin Gregorie < XXXX@XXXXX.COM > writes:




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
 
 
 

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

Post by ClassCastE » Tue, 15 Feb 2011 20:17:38


How about we use a real language:

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

;)
 
 
 

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

Post by Lew » Tue, 15 Feb 2011 21:08:07


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.