从执行命令多行程序中获取输出

getting output from executing a command multi line program

我有一个 eclipse 界面 Java Swing.This 界面有按钮和编辑器窗格。当我点击"compile"按钮时,我在后台运行命令行并按下命令行上所有结果的编辑器面板区域。我尝试使用 textarea,因为我无法使用编辑器窗格来做到这一点。但是现在它只打印 The Last Line 我该如何解决这个问题?

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

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

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