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?

Ross
  • 9,652
  • 8
  • 35
  • 35

3 Answers3

12

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
  • 17,736
  • 15
  • 72
  • 92
10
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
  • 6,930
  • 3
  • 23
  • 27
0

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
  • 273
  • 1
  • 6
  • 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 Jan 20 '09 at 00:24