为什么同一命令在bash脚本中有效,而在Java Runtime中却没有?

时间:2015-02-20 03:40:01

标签: java bash

命令" cat~ / desktop / b.mpg~ / desktop / b2.mpg> 〜桌面/ intermediate_all.mpg"似乎没有单独通过Java Runtime工作(如下例所示);

public class Test {
    public static void main(final String[] args)  {
        String[] cmd = {"cat ~/desktop/b.mpg ~/desktop/b2.mpg > ~desktop/intermediate_all.mpg"};
        try { Runtime.getRuntime().exec(cmd);  }
        catch (IOException e) { e.printStackTrace();}
    }
}


但是,当放入.sh文件时,就像在第二个例子中一样,它工作得很好....

public class Test {
    public static void main(final String[] args)  {
        try { Runtime.getRuntime().exec("/users/nn/desktop/configure.sh"); }
        catch (IOException e) { e.printStackTrace();}
    }
}


enter image description here

有人可以告诉我从bash脚本转到直接Java Runtime时基本过程丢失了吗?仅供参考,我正在使用OSX,已经尝试过使用绝对文件路径,并且了解Process Builder(具有相同的效果)比使用Java Runtim更受欢迎 - 正如在此论坛上已经说过一千次,所以让我们避免挨打那个死马。

由于

4 个答案:

答案 0 :(得分:1)

正在执行的命令是带有参数的cat。该命令及其参数必须是数组的单独元素。

此外,您无法使用Runtime.exec()重定向 - 您必须使用ProcessBuilder

试试这个:

ProcessBuilder pb = new ProcessBuilder("cat", "~/desktop/b.mpg", "~/desktop/b2.mpg");
pb.redirectOutput(new File("~/desktop/intermediate_all.mpg"));
Process p = pb.start();

可能无法理解shell位置~,因此您可能必须使用文件的完整绝对路径

答案 1 :(得分:0)

试试这个:

Runtime.getRuntime().exec(new String[] {
    "/bin/bash", "-c", 
    "cat ~/desktop/b.mpg ~/desktop/b2.mpg > ~/desktop/intermediate_all.mpg" })

答案 2 :(得分:0)

因为在第二种情况下,您正在有效地运行"bash", "-c", "cat etc >file",其中Bash负责为您解析重定向。重定向是shell的一个特性,而不是cat的特征;如果您在没有shell的情况下运行原始进程,则无法使用shell的功能。

答案 3 :(得分:-1)

你的java代码中的

〜/ desktop / b.mpg~ / desktop / b2.mpg> ~desktop / intermediate_all.mpg, 你必须在>之后给出完整的路径〜/桌面/ intermediate_all.mpg

相关问题