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

空扰寡人 提交于 2019-12-04 04:37:11

问题


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?


回答1:


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.




回答2:


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.




回答3:


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;
    }
}


来源:https://stackoverflow.com/questions/455695/what-is-the-best-way-to-read-a-text-file-two-lines-at-a-time-in-java

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