What is the best way to read a text file two lines at a time in Java?

天涯浪子 提交于 2019-12-01 21:10:55

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.

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.

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;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!