0

Through the following code, I can execute and get the shell command, and get the output, but only after the end of the process, can I get the standard output. How can I get the real-time output when the process is executing

         Process process = Runtime.getRuntime().exec(command);
         // close process's output stream.
         process.getOutputStream().close();

         pIn = process.getInputStream();
         InputStreamReader inputStreamReader = new InputStreamReader(pin, "UTF-8");
         bufferedReader = new BufferedReader(inputStreamReader);
         String line = null;
         while ((line = bufferedReader.readLine()) != null) {
             this.buf.append(line + "\n");
         }
        
        process.waitfor();
Question
  • 1
  • 2
  • This question answers yours: https://stackoverflow.com/questions/38821224/java-use-exec-and-read-output-while-program-is-still-running – Pawel Veselov Apr 15 '21 at 22:07

2 Answers2

0

you can use process builder to read response of command executed

         ProcessBuilder pb = new ProcessBuilder();
            pb.command(cmd);
            Process proc = pb.start();
            proc.waitFor();

            InputStream inputStream = proc.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String responseLine = "";
            StringBuilder output = new StringBuilder();
            while (( responseLine = reader.readLine())!= null) {
                output.append(responseLine + "\n");
            }
sanjeevRm
  • 1,541
  • 2
  • 13
  • 24
  • Your answer is quite close, but it does not work in real-time because it contains `proc.waitFor();`. hence it first waits for the process to exit and then start processing the output. – Robert Apr 14 '21 at 11:51
  • I just use this method, but I can't get real-time output – Question Apr 15 '21 at 06:19
0

Here is one way to display the output from the command in real time by redirecting the output to the same as those of the java process.

ProcessBuilder pb = new ProcessBuilder();
pb.command("./a-script.sh")
pb.inheritIO() // 
def proc = pb.start()
proc.waitFor()
pbthorste
  • 309
  • 2
  • 6