java - 每当我从代码执行终端命令时,它都会给出 "cannot run program"错误=2 没有这样的文件或目录

标签 java macos unix command

使用此代码并出现错误: 尝试 { 进程 p = Runtime.getRuntime().exec(“(lsof -i:10723 | grep node | awk ‘{print $2;}’)“);

        BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));

        BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));

        // read the output from the command
        String s = null;
        System.out.println(“Here is the standard output of the command:\n”);
        while ((s = stdInput.readLine()) != null) {
            System.out.println(s);
        }

        // read any errors from the attempted command

        System.out.println(“Here is the standard error of the command (if any):\n”);
        while ((s = stdError.readLine()) != null) {
            System.out.println(s);
        }
    } catch (Exception e) {
    e.printStackTrace();
    }

最佳答案

问题是你不能这样做:

exec("(lsof -i:10723 | grep node | awk '{print $2;}')");

exec 方法不理解 shell 语法。它将将该命令字符串拆分为命令名称和看到空格的参数。

因此 exec 尝试执行的命令名称是 (lsof ...,该命令不存在。因此出现错误消息。

如果你想使用exec运行管道,简单的方法是使用shell;例如

exec(new String[] {"sh", "-c",
                   "(lsof -i:10723 | grep node | awk '{print $2;}')"})

关于java - 每当我从代码执行终端命令时,它都会给出 "cannot run program"错误=2 没有这样的文件或目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48398871/

相关文章:

java - 有什么方法可以从包含 HashMap 的 ArrayList 的 HashMap 中获取值列表吗?

java - Android Foursquare accessToken : How to get accessToken from inner class?

java - 转换实现 Runnable 的对象

objective-c - 如何在另一个 NSView 下阻止 NSView 事件?

ios - 如果我安装 xcode 6,它会取代我的旧 Xcode 和其他问题吗

ios - 使用 CocoaHTTPServer 流式传输视频

JAVA hibernate/webservice - 时间戳问题

linux - 如何在 vi 编辑器中一次搜索 3 个字符串?

linux - 交换两个符号链接(symbolic link)

bash - 删除所有以小写字符开头的行