简体   繁体   中英

Executing a command

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM