I\'m using the runtime to run command prompt commands from my Java program. However, I\'m not aware of how I can get the output the command returns.
Here is my code:
@Senthil and @Arend answer (https://stackoverflow.com/a/5711150/2268559) mentioned ProcessBuilder
. Here is the example using ProcessBuilder
with specifying environment variables and working folder for the command:
ProcessBuilder pb = new ProcessBuilder("ls", "-a", "-l");
Map env = pb.environment();
// If you want clean environment, call env.clear() first
//env.clear();
env.put("VAR1", "myValue");
env.remove("OTHERVAR");
env.put("VAR2", env.get("VAR1") + "suffix");
File workingFolder = new File("/home/user");
pb.directory(workingFolder);
Process proc = pb.start();
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
// Read the output from the command:
System.out.println("Here is the standard output of the command:\n");
String s = null;
while ((s = stdInput.readLine()) != null)
System.out.println(s);
// Read any errors from the attempted command:
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null)
System.out.println(s);