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

R

Robin Wenger

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
 
L

Lew

Peter said:
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|
|_____|_____|
|===========|
 
J

Jim Janney

D

Donkey Hottie

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

Real Gagnon

Lew said:
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.
 
K

Kevin McMurtrie

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);
}
}
}
 
L

Lew

Kevin said:
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|
|_____|_____|
|===========|
 
M

Martin Gregorie

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.
 
R

Roedy Green

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.
..
 
J

Jim Janney

Martin Gregorie said:
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.
 
C

ClassCastException

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

;)
 
L

Lew

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,540
Members
45,025
Latest member
KetoRushACVFitness

Latest Threads

Top