繁体   English   中英

执行命令

[英]Executing 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();
    }
}

但是结果却不是我所期望的:

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

我究竟做错了什么? Ubuntu 18.04。

Runtime.exec无法运行这样的任意shell / terminal命令。

您必须运行bash程序,然后将命令作为参数发送到bash。 Bash将为您完成这项工作。

https://stackoverflow.com/a/15356451/1364747

这是特定于操作系统的。 在不同的操作系统上,它可能是不同的命令/终端。 另外,您可能需要知道该程序的路径。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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