Discussion: Execute bash command in Java
In the previous quiz, Online Java Quiz, we tested our experience gained from the course.
Member
7 messages from 7 displayed.
//= Settings::TRACKING_CODE_B ?> //= Settings::TRACKING_CODE ?>
In the previous quiz, Online Java Quiz, we tested our experience gained from the course.
You can use ProcessBuilder: http://docs.oracle.com/…Builder.html
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:
private void 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).
I've tried to execute this command:
new String[] {"bin/bash","-c","echo password| sudo -S ls"},
Results in: Cannot run program "bin/bash": error=2, No such file or directory
I'm using Debian.
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".
7 messages from 7 displayed.