получение результата от выполнения программы командной строки - PullRequest
0 голосов
/ 27 июня 2019

У меня есть интерфейс с затмением 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 голосов
/ 27 июня 2019

Вы сбрасываете текст каждый раз, поэтому сохраняется только последняя строка. Сделайте это:

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