0

I couldn't find a better way to word the question but here is what I would like to do. I am using the RandomAccessFile class to do various things with an input file.

I would like to check to make sure the next line file is not null before attempting to store the line.

So I use the code:

while (raf.readLine() ! = null)
{
     //Do things with that line
}

But once I call raf.readLine() in the while loop I iterate to the next line without actually storing the line. Is there I way I can store the line that way read in the while loop?

Gasper Gulotta
  • 159
  • 3
  • 9
  • See the comments to http://stackoverflow.com/questions/4677411/iterating-over-the-content-of-a-text-file-line-by-line-is-there-a-best-practic. Unfortunately, `readLine()` can throw `IOException`, so one can't directly adapt a `Bufferedreader` to be an `Iterable`. Apache Commons-IO has a `LineIterator` class, however. – Eric Jablow Jun 04 '13 at 17:59

2 Answers2

6

One common way to do this is something like:

while ((myLine = raf.readLine()) != null)
{
     //Do things with that line, held in myLine
}

An assignment evaluates to the value that was assigned.

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
1

You can declare the variable to store the line outside the loop and initialize it with the first line, and read the next line at the end of the loop, then check if that variable is null in the loop condition.

String currentLine = raf.readLine();
while(currentLine != null)
{
    //do stuff
    currentLine = raf.readLine();
}
Blake Hood
  • 314
  • 3
  • 12
  • Its much easier to have current line as a String, and then have the while manage it in 1 place – exussum Jun 04 '13 at 17:48
  • Well that was a fast downvote. Whoever did it, I'm sorry a couple other people posted very similar answers while I was typing mine. – Blake Hood Jun 04 '13 at 17:49
  • 1
    This is the style I prefer. I have a natural aversion to assignment statements in if/while conditions. And the style is easily extended to "read" operations that take several steps, unlike the embedded assignment approach. – Hot Licks Jun 04 '13 at 17:52
  • 1
    @BlakeHood you don't have to apologize for anything, this is a legitimate, and different solution to the problem. – Benjamin Gruenbaum Jun 04 '13 at 17:53