【问题标题】:Runtime.exec - fine for 'echo' 'but not for cat...Runtime.exec - 适用于“回声”,但不适用于猫...
【发布时间】:2012-08-09 13:48:52
【问题描述】:

我在使用 r.exec 调用一些简单的命令行函数时遇到问题 - 出于某种原因,给定文件 X 命令 'echo full/path/to/X' 工作正常(在显示中和使用 'p.exitValue()==0',但 'cat full/path/to/X' 没有(并且有 'p.exitValue ()==1') - 'cat' 和 'echo' 都存在于我的 OSX 上的 /bin/ 中 - 我错过了什么吗?代码如下(碰巧,欢迎任何改进代码的建议... )

private String takeCommand(Runtime r, String command) throws IOException {
        String returnValue;
        System.out.println("We are given the command" + command);
        Process p = r.exec(command.split(" "));
        InputStream in = p.getInputStream();
        BufferedInputStream buf = new BufferedInputStream(in);
        InputStreamReader inread = new InputStreamReader(buf);
        BufferedReader bufferedreader = new BufferedReader(inread);
        // Read the ls output
        String line;
        returnValue = "";
        while ((line = bufferedreader.readLine()) != null) {
            System.out.println(line);
            returnValue = returnValue + line;
        }
        try {// Check for  failure
            if (p.waitFor() != 0) {
                System.out.println("XXXXexit value = " + p.exitValue());
            }
        } catch (InterruptedException e) {
            System.err.println(e);
        } finally {
            // Close the InputStream
            bufferedreader.close();
            inread.close();
            buf.close();
            in.close();
        }
        try {// should slow this down a little
            p.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return returnValue;
    }

【问题讨论】:

  • 如果你使用 ProcessBuilder,你可以结合 stdout 和 stderr,这样你就只有一个流可以读取。

标签: java command-line runtime.exec cat


【解决方案1】:

您应该异步使用标准输出和标准错误

否则,命令的输出可能会阻塞输入缓冲区,然后一切都会停止(这可能是您的cat 命令发生的情况,因为它会转储比echo 更多的信息)。

我也不希望必须给waitFor() 打两次电话。

查看this SO answer 了解更多关于输出消耗的信息,查看this JavaWorld 文章了解更多Runtime.exec() 陷阱。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-18
    • 1970-01-01
    • 2021-05-24
    • 2016-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多