Reputation: 429
I'm trying to execute a command:
public static void main(String[] args) {
int buffer;
StringBuilder res = new StringBuilder();
Process proc;
try {
proc = Runtime.getRuntime().exec("cat /proc/stat | grep 'btime' | awk '{print $2}'");
BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
String line;
while ((line=reader.readLine())!=null) {
System.out.println(line);
}
proc.waitFor();
} catch (Exception e) {
e.printStackTrace();
}
}
But the result is not what I expected:
cat: '|': No such file or directory
cat: grep: No such file or directory
cat: "'btime'": No such file or directory
cat: '|': No such file or directory
cat: awk: No such file or directory
cat: ''\''{print': No such file or directory
cat: '$2}'\''': No such file or directory
What am I doing wrong? Ubuntu 18.04.
Upvotes: 1
Views: 111
Reputation: 4243
Runtime.exec cannot run arbitrary shell/terminal commands like this.
You have to run the bash program and then send your command as parameter to bash. Bash will do the job for you.
https://stackoverflow.com/a/15356451/1364747
This is OS specific. On a different OS it might be a different command/terminal. Also you might need to know the path to that program.
Upvotes: 2