You can then use somethink like proc.getInputStream() or
proc.getOutputStream() to get output or set input (in case you are
running some interactive command).
Thanks for reply. I managed to parse the stream using the getInputStream()
method:
try {
Process p = Runtime.getRuntime().exec(commands);
p.waitFor();
extractOutput(p.getInputStream(), out, "");
extractOutput(p.getErrorStream(), out, "[ERR]: ");
} catch (IOException e) {
System.err.println("There was a problem starting the command (possibly a typo?): " + e);
} catch (InterruptedException e) {
System.err.println("There was an internal problem running the command: " + e);
}
And the extractOutput() method:
privatevoid extractOutput(InputStream stream, Path dest, String prefix) {
BufferedReader r = new BufferedReader(new InputStreamReader(stream));
String line;
try {
while ((line = r.readLine()) != null) {
System.out.println(prefix + line);
Files.write(dest, (prefix + line + '\n').getBytes("UTF-8"), StandardOpenOption.CREATE, StandardOpenOption.APPEND);
System.out.println("");
}
} catch (IOException e) {
System.err.println("Couldn't write program's output to the file " + dest.toString() + ": " + e);
}
}
However, I've encountered a new problem - I need to execute a command which
requires root privileges (sudo).
Well it says where is the problem - "bin/bash/ does not exist. Simple "bash"
didn't work? If you want to use absolute path, you need to put slash in the
beginning - "/bin/bash".