正在执行的Processbuilder输出

时间:2018-06-13 21:26:43

标签: java shell

我希望shell命令的输出在执行shell命令时转到我的java程序中的textArea而不是在它完成之后。

等待进程完成然后显示输出的当前代码:

ProcessBuilder builder = new ProcessBuilder("shell_command.sh");

builder.redirectErrorStream(true);

try {
    Process p = builder.start();
    String s;
    BufferedReader stdout = new BufferedReader (
        new InputStreamReader(p.getInputStream()));

    while ((s = stdout.readLine()) != null) {
        logPanel.addText(s + "\r\n"); // adds text to a textArea
    }

    System.out.println("Exit value: " + p.waitFor());
    p.getInputStream().close();
    p.getOutputStream().close();
    p.getErrorStream().close();
} catch (Exception ex) {
    ex.printStackTrace();
}

1 个答案:

答案 0 :(得分:0)

在UI线程中......

(new Thread(new ShellCommand(logPanel) ) ).start();

新班......

class ShellCommand implements Runnable {

    LogPanel logPanel; // textArea

    ShellCommand(LogPanel logPanel) {
        this.logPanel = logPanel;
    }

    public void run() {

        try {
            ProcessBuilder builder = new ProcessBuilder("shell_command.sh");

            builder.redirectErrorStream(true);

            Process p = builder.start();
            String s;
            BufferedReader stdout = new BufferedReader(new 
                InputStreamReader(p.getInputStream()));
            while ((s = stdout.readLine()) != null) {
                logPanel.addText(s + "\r\n");
            }

            System.out.println("Exit value: " + p.waitFor());
            p.getInputStream().close();
            p.getOutputStream().close();
            p.getErrorStream().close();

            JOptionPane.showMessageDialog(null, "Done", "Message",
                 JOptionPane.INFORMATION_MESSAGE);

            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
}