Java - 反向读取行的输出

时间:2012-06-11 21:17:49

标签: java line reverse

以下例程输出从国际象棋引擎移动到JTextArea

public void getEngineOutputOriginal(Process engine) 
{
    try {           
        BufferedReader reader =
          new BufferedReader (new InputStreamReader (engine.getInputStream ()), 1);
        String lineRead = null;
        // send engine analysis to print method
        while ((lineRead = reader.readLine ()) != null)
           Application.showEngineAnalysis (lineRead);
    }
    catch (Exception e) {
                      e.printStackTrace();
    }
}

示例输出

           12     3.49  39/40?  2. b4      (656Knps)             
           12     3.49  40/40?  2. Nd5     (656Knps)             
           12->   3.51   0.04   2. Bxf4 Be6 3. Be3 Qa5 4. Nd5 Qxd2
           13     3.51   1/40?  2. Bxf4    (655Knps)   

是否可以反转过程,以便最后一行读取始终显示在顶部而不是底部,如下所示:

           13     3.51   1/40?  2. Bxf4    (655Knps)   
           12->   3.51   0.04   2. Bxf4 Be6 3. Be3 Qa5 4. Nd5 Qxd2
           12     3.49  40/40?  2. Nd5     (656Knps)             
           12     3.49  39/40?  2. b4      (656Knps)     

我研究过Google,但找不到解决方案

1 个答案:

答案 0 :(得分:2)

当然!一种选择就是将行缓冲到ArrayList,然后在结尾以相反的顺序显示它们:

List<String> lines = new ArrayList<String>();

/* Add all lines from the file to the buffer. */
while((lineRead = reader.readLine()) != null) {
    lines.add(lineRead);
}

/* Replay them in reverse order. */
for (int i = lines.size() - 1; i >= 0; i--) {
     Application.showEngineAnalysis(lines.get(i));
}

从概念上讲,您可以将此视为堆叠,将所有线条推入堆叠,然后一次将其弹出一个。

希望这有帮助!