Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.java.programmer > #25827 > unrolled thread
| Started by | Lew <noone@lewscanon.com> |
|---|---|
| First post | 2011-02-11 07:51 -0500 |
| Last post | 2011-02-11 22:34 +0000 |
| Articles | 2 — 2 participants |
Back to article view | Back to comp.lang.java.programmer
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
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
| From | Lew <noone@lewscanon.com> |
|---|---|
| Date | 2011-02-11 07:51 -0500 |
| Subject | Re: Shortest way to read all lines (one by one) from a text file? |
| Message-ID | <ij3bb4$eal$1@news.albasani.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?
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|
|_____|_____|
|===========|
[toc] | [next] | [standalone]
| From | Real Gagnon <realgag+usenet@geocities.com> |
|---|---|
| Date | 2011-02-11 22:34 +0000 |
| Message-ID | <Xns9E89B2DE6294rgagnoncom@69.16.186.8> |
| In reply to | #25827 |
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
[toc] | [prev] | [standalone]
Back to top | Article view | comp.lang.java.programmer
csiph-web