Using CMD as a Process

后端 未结 6 1653
無奈伤痛
無奈伤痛 2020-12-22 09:38

I\'m trying to run commands straight through the CMD on Windows (Terminal on Linux). I have the following code. It\'s acting very strangely. First, when run the program does

6条回答
  •  旧时难觅i
    2020-12-22 10:13

    You need to do this work in a Thread. For example to log the standard output:

    Process process = Runtime.getRuntime().exec(command);
    LogStreamReader lsr = new LogStreamReader(process.getInputStream());
    Thread thread = new Thread(lsr, "LogStreamReader");
    thread.start();
    
    
    public class LogStreamReader implements Runnable {
    
        private BufferedReader reader;
    
        public LoggingStreamReader(InputStream is) {
            this.reader = new BufferedReader(new InputStreamReader(is));
        }
    
        public void run() {
            try {
                String line = reader.readLine();
                while (line != null) {
                    System.out.println(line);
                    line = reader.readLine();
                }
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    

    Then you need a second thread for input handling. And you might want to deal with stderr just like stdout.

提交回复
热议问题