Hello i have some question about java. here is my code:
public static void main(String[] args) throws Exception { Process pr = Runtime.getRuntime().exec("java -version"); BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream())); String line; while ((line = in.readLine()) != null) { System.out.println(line); } pr.waitFor(); System.out.println("ok!"); in.close(); System.exit(0); }
in that code i'am trying to get a java version command execute is ok, but i can't read the output it just return null. Why?
You can get the Input-, Output- and Errorstream. In your case you want pr. getInputStream(). Read from that, that is connected to the output of the process.
exec(String command) method executes the specified string command in a separate process. This is a convenience method. An invocation of the form exec(command) behaves in exactly the same way as the invocation exec(command, null, null).
public ProcessBuilder(String... command) Constructs a process builder with the specified operating system program and arguments. This is a convenience constructor that sets the process builder's command to a string list containing the same strings as the command array, in the same order.
Use getErrorStream().
BufferedReader in = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
EDIT:
You can use ProcessBuilder (and also read the documentation)
ProcessBuilder ps=new ProcessBuilder("java.exe","-version"); //From the DOC: Initially, this property is false, meaning that the //standard output and error output of a subprocess are sent to two //separate streams ps.redirectErrorStream(true); Process pr = ps.start(); BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream())); String line; while ((line = in.readLine()) != null) { System.out.println(line); } pr.waitFor(); System.out.println("ok!"); in.close(); System.exit(0);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With