Reputation: 9928
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?
Upvotes: 3
Views: 10122
Reputation: 273
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;
}
}
Upvotes: 0
Reputation: 7045
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.
Upvotes: 10
Reputation: 18043
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.
Upvotes: 12