Javaで一度に2行のテキストファイルを読むための最良の方法は何ですか?

StackOverflow https://stackoverflow.com/questions/455695

  •  19-08-2019
  •  | 
  •  

質問

BufferedReader in;

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

これは、ファイルを1行ずつ処理する方法です。ただし、この場合、反復ごとに 2 行のテキストをプロセッサに送信します。 (処理中のテキストファイルは、基本的に2行に1つのレコードを格納するため、毎回1つのレコードをプロセッサに送信しています。)

Javaでこれを行う最良の方法は何ですか?

役に立ちましたか?

解決

2行だけを読むのはなぜですか?

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

これは、入力ファイルに完全な2行のデータセットがあることに依存できることを前提としています。

他のヒント

BufferedReader in;
String line1, line2;

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

または、必要に応じて連結することもできます。

次のようにコードをリファクタリングします。

RecordReader recordReader;
Processor processor;

public void processRecords() {
    Record record;

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

もちろんその場合、このクラスに何らかの方法で正しいレコードリーダーを挿入する必要がありますが、それは問題になりません。

RecordReaderの実装の1つは次のようになります。

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;
    }
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top