java - 为什么下面的代码不起作用?

标签 java linux command

<分区>

我正在尝试通过 java 在 linux 中运行 shell 命令。大多数命令都有效,但是当我运行以下命令时,我得到了一个 execption,尽管它在 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: 没有那个文件或目录

最佳答案

问题是重定向。

cat: >: No such file or directory

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

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

确实,> 不是一个文件。它根本不是一个文件。它是一个重定向输出的 shell 操作符。

您需要使用ProcessBuilder 来重定向:

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

关于java - 为什么下面的代码不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34293946/

相关文章:

java - Android TextToSpeech 只是拼写短词而不是发音

linux - Google chrome 与 oracle-xe 的内核参数冲突

c++ - Linux进程的默认分配堆大小

ruby - 通过 nohup 运行 ruby​​ 脚本时,为什么不写入 nohup.out

mysql - Laravel Eloquent 替换

javascript - Jasmine JS覆盖没有仪器不工作

java - 在 JavaFX 中绘制节点

java - 在此 java 程序中找不到符号消息

java - newDocument( View 模态)时无法预处理面板动态数据源以设置默认值

java - 从 cmd 运行 Jar 相关的 .Java