Martin Dvoracek
Martin Dvoracek

Reputation: 1738

How to run a command in unix shell and then get the output back from/to java application

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?

Upvotes: 0

Views: 243

Answers (1)

RamonBoza
RamonBoza

Reputation: 9038

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

Upvotes: 3

Related Questions