附加到JTextArea?

时间:2012-08-12 01:23:33

标签: java swing jtextarea runtime.exec

  

可能重复:
  Capturing stdout when calling Runtime.exec

以下是问题,请输入以下代码,

public void CMD() {
    try
    {            
        Runtime rt = Runtime.getRuntime();

        Process proc = rt.exec("dir");
        InputStream stdin = proc.getInputStream();
        InputStreamReader isr = new InputStreamReader(stdin);
        BufferedReader br = new BufferedReader(isr);
        String line = null;
        System.out.println("<OUTPUT>");
        while ( (line = br.readLine()) != null)
            System.out.println(line);
        System.out.println("</OUTPUT>");
        int exitVal = proc.waitFor();            
        System.out.println("Process exitValue: " + exitVal);
    } catch (Throwable t)
    {
        t.printStackTrace();
    }
}

如何将输出传输到jTextArea?

2 个答案:

答案 0 :(得分:2)

这很简单:

    while ( (line = br.readLine()) != null) {
        textArea.append(line + "\n");
    }

答案 1 :(得分:1)

我认为最好将UI与处理分开 - 这个概念称为分层。我反对在这种方法中看到标记。最好将其与实际从运行时进程中获取信息分开。

我建议您阅读更新的执行流程的方法。

  1. http://www.javaworld.com/jw-12-2000/jw-1229-traps.html
  2. http://www.java-tips.org/java-se-tips/java.util/from-runtime.exec-to-processbuilder.html