views:

605

answers:

3
BufferedReader in;

String line;
while ((line = in.readLine() != null) {
    processor.doStuffWith(line);
}

This is how I would process a file line-by-line. In this case, however, I want to send two lines of text to the processor in every iteration. (The text file I'm processing essentially stores one record on two lines, so I'm sending a single record to the processor each time.)

What's the best way of doing this in Java?

+9  A: 

Why not just read two lines?

BufferedReader in;
String line;
while ((line = in.readLine() != null) {
    processor.doStuffWith(line, in.readLine());
}

This assumes that you can rely on having full 2-line data sets in your input file.

martinus
+6  A: 
BufferedReader in;
String line1, line2;

while((line1 = in.readLine()) != null 
   && (line2 = in.readLine()) != null))
{
    processor.doStuffWith(line1, line2);
}

Or you could concatenate them if you wanted.

Adam Peck
A: 

I would refactor code to look somehow like this:

RecordReader recordReader;
Processor processor;

public void processRecords() {
    Record record;

    while ((record = recordReader.readRecord()) != null) {
     processor.processRecord(record);
    }
}

Of course in that case you have to somehow inject correct record reader in to this class but that should not be a problem.

One implementation of the RecordReader could look like this:

class BufferedRecordReader implements RecordReader
{
    BufferedReader in = null;

    BufferedRecordReader(BufferedReader in)
    {
     this.in = in;
    }
    public Record readRecord()
    {
     String line = in.readLine();

     if (line == null) {
      return null;
     }

     Record r = new Record(line, in.readLine());

     return r;
    }
}
jan
Thanks, jan. My code actually already looks like this--I was trying to figure out how to best write the equivalent of your "BufferedRecordReader" implementation.
Ross