Get output from a BAT file using Java

I am trying to run a .bat file and get the result. I can run it, but I can not get the results in Java:

String cmd = "cmd /c start C:\\workspace\\temp.bat"; Runtime r = Runtime.getRuntime(); Process pr = r.exec(cmd); BufferedReader stdInput = new BufferedReader( new InputStreamReader( pr.getInputStream() )); String s ; while ((s = stdInput.readLine()) != null) { System.out.println(s); } 

The result is null . I don’t know why I get it. Please note that I am using Windows 7.

+6
source share
3 answers

Using "cmd / c start [...]" to run the batch file will create a subprocess instead of running the batch file directly.

Thus, you will not have access to its output. For it to work, you must use:

 String cmd = "C:\\workspace\\temp.bat"; 

It works under Windows XP.

+4
source

You need to start a new thread, which will read the terminal output stream and copy it to the console after calling process.waitFor() .

Do something like:

 String line; Process p = Runtime.getRuntime().exec(...); BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream())); while ((line = input.readLine()) != null) { System.out.println(line); } input.close(); 

The best approach would be to use the ProcessBuilder class and try writing something like:

 ProcessBuilder builder = new ProcessBuilder("/bin/bash"); builder.redirectInput(); Process process = builder.start(); while ((line = reader.readLine ()) != null) { System.out.println ("Stdout: " + line); } 
+3
source
 BufferedReader stdInput = new BufferedReader(new InputStreamReader( pr.getErrorStream() )); 

use instead

 BufferedReader stdInput = new BufferedReader(new InputStreamReader( pr.getInputStream )); 
-1
source

Source: https://habr.com/ru/post/947091/


All Articles