【问题标题】:What is the best way to read a text file two lines at a time in Java?在 Java 中一次读取两行文本文件的最佳方法是什么?
【发布时间】:2010-10-02 03:00:52
【问题描述】:
BufferedReader in;

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

这就是我逐行处理文件的方式。然而,在这种情况下,我想在每次迭代中向处理器发送 行文本。 (我正在处理的文本文件实际上将一条记录存储在两行中,因此我每次都向处理器发送一条记录。)

在 Java 中最好的方法是什么?

【问题讨论】:

    标签: java text-files fileparsing


    【解决方案1】:

    为什么不读两行?

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

    这假设您可以依赖输入文件中包含完整的 2 行数据集。

    【讨论】:

      【解决方案2】:
      BufferedReader in;
      String line1, line2;
      
      while((line1 = in.readLine()) != null 
         && (line2 = in.readLine()) != null))
      {
          processor.doStuffWith(line1, line2);
      }
      

      或者你可以根据需要连接它们。

      【讨论】:

        【解决方案3】:

        我会重构代码,使其看起来像这样:

        RecordReader recordReader;
        Processor processor;
        
        public void processRecords() {
            Record record;
        
            while ((record = recordReader.readRecord()) != null) {
                processor.processRecord(record);
            }
        }
        

        当然,在这种情况下,您必须以某种方式将正确的记录读取器注入到此类中,但这应该不是问题。

        RecordReader 的一个实现可能如下所示:

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

        【讨论】:

        • 谢谢,一月。我的代码实际上已经看起来像这样——我试图弄清楚如何最好地编写与“BufferedRecordReader”实现等效的方法。
        猜你喜欢
        • 1970-01-01
        • 2011-12-23
        • 1970-01-01
        • 2011-09-28
        • 1970-01-01
        • 2022-11-17
        • 2021-01-14
        • 1970-01-01
        相关资源
        最近更新 更多