【问题标题】:Why the following code doesn't work? [duplicate]为什么下面的代码不起作用? [复制]
【发布时间】:2016-03-21 12:32:12
【问题描述】:

我正在尝试通过 java 在 linux 中运行 shell 命令。大多数命令都有效,但是当我运行以下命令时,我得到一个执行,尽管它在 shell 中有效:

    String command = "cat b.jpg f1.zip > pic2.jpg";

    String s = null;
    try {
        Process p = Runtime.getRuntime().exec(command);

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

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

        System.out.println("Here is the standard output of the command:\n");

        while ((s = stdInput.readLine()) != null) {
            System.out.println(s);
        }
        System.out.println("Here is the standard error of the command (if any):\n");
        while ((s = stdError.readLine()) != null) {
            System.out.println(s);
        }
        System.exit(0);
    }
    catch (IOException e) {
        System.out.println("exception happened - here's what I know: ");
        e.printStackTrace();
        System.exit(-1);
    }

我在控制台中收到错误:

cat: >: 没有这样的文件或目录

cat: pic2.jpg: 没有这样的文件或目录

【问题讨论】:

标签: java linux command


【解决方案1】:

问题在于重定向。

cat:>: 没有这样的文件或目录

这个错误信息的解释方式:

  • 程序cat 试图告诉您一个问题
  • 问题是没有名为>的文件

确实,> 不是文件。它根本不打算作为文件。它是一个用于重定向输出的 shell 运算符。

需要使用ProcessBuilder进行重定向:

ProcessBuilder builder = new ProcessBuilder("cat", "b.jpg", "f1.zip");
builder.redirectOutput(new File("pic2.jpg"));
Process p = builder.start();

【讨论】:

    【解决方案2】:

    当你运行一个命令时,它不会像 bash 那样启动一个 shell,除非你明确地这样做。这意味着您正在运行 cat 并带有四个参数 b.jpg f1.zip > pic2.jpg 最后两个文件名不存在,因此您会收到错误消息。

    您可能想要的是以下内容。

    String command = "sh -c 'cat b.jpg f1.zip > pic2.jpg'";
    

    这将运行sh,它将>视为重定向输出的特殊字符。

    【讨论】:

      【解决方案3】:

      因为你需要启动一个shell(例如/bin/bash)来执行你的shell命令,所以替换:

      String command = "cat b.jpg f1.zip > pic2.jpg";
      

      String command = "bash -c 'cat b.jpg f1.zip > pic2.jpg'";
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-06-15
        • 1970-01-01
        • 2014-09-26
        • 1970-01-01
        • 2018-12-15
        • 2013-06-20
        • 1970-01-01
        相关资源
        最近更新 更多