通过执行命令多行程序获取输出

时间:2019-06-27 06:42:28

标签: java eclipse swing command line

我有一个带有Eclipse Java Swing的界面,该界面有按钮和编辑器窗格。当我单击“编译”按钮时,我在后台运行命令行,然后在命令行上按所有结果的编辑器面板区域。我尝试使用textarea是因为我无法使用编辑器窗格执行此操作。但是现在它仅打印“最后一行”。如何解决此问题?

btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

            Runtime rt = Runtime.getRuntime();  

            Process proc = null;
            try {
                proc = rt.exec("cmd /c cd process.txt");
            } catch (IOException e3) {
                // TODO Auto-generated catch block
                e3.printStackTrace();
            }

            BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream())); 
            BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

            // Read the output from the command
            System.out.println("Here is the standard output of the command:\n");
            String s = null;

            try {
                while ((s = stdInput.readLine()) != null) {



                    textArea.setText("\n"+s);


                }
            } catch (IOException e2) {
                // TODO Auto-generated catch block
                e2.printStackTrace();
            }

            // Read any errors from the attempted command
            System.out.println("Here is the standard error of the command (if any):\n");
            try {
                while ((s = stdError.readLine()) != null) {

                    textArea.setText("\n"+s);
                    }
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }

1 个答案:

答案 0 :(得分:0)

您每次都在重置文本,因此仅保留最后一行。这样做:

StringBuilder builder = new StringBuilder()
try {
    while ((s = stdInput.readLine()) != null) {
        builder.append('\n').append(s);
    }

    while ((s = stdError.readLine()) != null) {
        builder.append('\n').append(s);
    }

    textArea.setText(builder.toString();
} catch (IOException e2) {
    e2.printStackTrace();
}