简体   繁体   中英

Why does the same command work in a bash script but not in Java Runtime directly?

The command "cat ~/desktop/b.mpg ~/desktop/b2.mpg > ~desktop/intermediate_all.mpg" does not seem to work via Java Runtime alone (as seen in the example below);

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();}
    }
}


However, when put into a .sh file like in this second example it works just fine....

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


在此输入图像描述

Can anybody please tell me what the fundamental process is being lost when moving from a bash script to straight Java Runtime? FYI, I am using OSX, have already tried using absolute filepaths, and know about Process Builder (which has the same effect) is preferred to using Java Runtim--as has been stated a thousand times on this forum already, so lets avoid beating the dead horse on that one.

Thanks

The command being executed is cat with arguments. The command and its arguments must be separate elements of the array.

Also, you can't redirect using Runtime.exec() - you must use ProcessBuilder :

Try this:

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

It is likely that the shell location ~ will not be understood, so you may have to use the full absolute path for the files

Try this:

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

Because in the second case, you are effectively running "bash", "-c", "cat etc >file" where Bash takes care of parsing the redirection for you. Redirection is a feature of the shell, not of cat ; if you run the raw process without a shell, the features of the shell are not available to you.

在您的java代码〜/ desktop / b.mpg~/ desktop / b2.mpg> ~desktop / intermediate_all.mpg中,您必须在>〜/ desktop / intermediate_all.mpg之后给出完整路径

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM