1

I want to execute an operating system command in Java, and then print out it's returned value. Like this:

This is what I am trying...

String location_of_my_exe_and_some_parameters = "c:\\blabla.exe /hello -hi"; Runtime.getRuntime().exec(location_of_my_exe_and_some_parameters); 

I tried putting a System.out.print() on the beginning of my Runtime... line, but it failed. Because, apparently, getRuntime() returns a Runtime object.

Now, the problem is, when I execute the "blabla.exe /hello -hi" command in command line, I got a result like: "You executed some command, hurray!". But, in Java, I got nothing.

I tried putting the return value into a Runtime object, to an Object object. However, they both failed. How can I accomplish this?

Problem Solved - this is my solution

Process process = new ProcessBuilder(location, args).start(); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { System.out.println(line); } 

3 Answers 3

1

Notice that Runtime.exec(...) returns a Process object. You can use this object to capture its input stream and retrieve whatever it prints to the standard output:

Process p = Runtime.getRuntime().exec(location_of_my_exe_and_some_parameters); InputStream is = p.getInputStream(); // read process output from is 
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you very much. Thanks for being kind, polite and fast.
@John Doe: Make sure to mark the answer that was the most helpful to you as accepted for future readers to find it fast.
I think I can't mark or vote. I don't have sufficient "karma" for that.
@John Doe: You need 15 to vote, but you can mark at any score, even 1.
1

You can capture the output of a command using this:

 Runtime rt = Runtime.getRuntime(); Process pr = rt.exec(command); BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream())); String line=null; while((line=input.readLine()) != null) { log.info(line); } //This will wait for the return code of the process int exitVal = pr.waitFor(); 

Comments

0

UseProcessBuilder instead of Runtime.

Like:

Process process = new ProcessBuilder("c:\\blabla.exe","param1","param2").start();

Answer:

Process process = new ProcessBuilder("c:\\blabla.exe","/hello","-hi").start(); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; System.out.printf("Output of running %s is:", Arrays.toString(args)); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.