0

I know how to execute a shell command from my java app. It should be something like:

String command = "java -version";
Process proc = null;
try {
  proc = Runtime.getRuntime().exec(command);
}
catch (IOException e) {
System.out.print(e);
}

I want to get the output of this command back to my java app, without printing the output to some temporary file which I then read from my app. Is this possible?

1 Answer 1

3

You need to use ProcessBuilder

Process process = new ProcessBuilder(
"C:\\PathToExe\\exe.exe","param1","param2").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));

while ((line = br.readLine()) != null) {
  System.out.println(line);
}

code that is already found on stackoverflow Execute external program in java

Sign up to request clarification or add additional context in comments.

1 Comment

Note that processbuilder has nothing at all to do with the solution, which is simply to use the getinputstream method in the process class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.