Execute external program from Java

后端 未结 3 1676
感情败类
感情败类 2020-12-03 22:30

I am trying to execute a program from the Java code. Here is my code:

public static void main(String argv[]) {
    try {
      String line;
      Process p =         


        
3条回答
  •  无人及你
    2020-12-03 23:03

    To get the redirection to work as written, you need to do this:

    Process p = Runtime.getRuntime().exec(
          new String[]{"/bin/bash", "-c", "ls > OutputFileNames.txt"});
    

    The problem you were running into is the simple-minded way that that Runtime.exec(String) splits a command line into arguments.

    If you were to run that command (as is) at a shell prompt, you would have had to have entered it as:

    $ /bin/bash -c "ls > OutputFileNames.txt"
    

    because the "-c" option for "bash" requires the command line for the spawned shell as a single shell argument. But if you were to put the naked quotes into the Java String, the Runtime.exec(String) method still get the splitting wrong. The only solution is to provide the command arguments as an array.

提交回复
热议问题