【问题标题】:Executing a command执行命令
【发布时间】:2019-04-20 13:19:10
【问题描述】:

我正在尝试执行一个命令:

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。

【问题讨论】:

标签: java


【解决方案1】:

Runtime.exec 不能像这样运行任意 shell/终端命令。

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-05
    • 2012-07-15
    • 2017-07-04
    • 1970-01-01
    • 1970-01-01
    • 2011-06-15
    • 1970-01-01
    相关资源
    最近更新 更多