Execute Unix system command from JAVA problem

孤人 提交于 2019-12-04 14:26:53
Christian.K

My Java is more than rusty, so please be gentle. ;-)

  1. Runtime.exec() does not automatically use the shell to execute the command you passed, so the IO redirection is not doing anything.

  2. If you just use:

    "/bin/sh -c system_profiler -detailLevel full > path/file.plist"
    

    Then the string will be tokenized into:

    { "/bin/sh", "-c", "system_profiler", "-detailLevel", "full", ">", "path/file.plist" }
    

    Which also wouldn't work, because -c only expects a single argument.

Try this instead:

String[] cmd = { "/bin/sh", "-c", "system_profiler -detailLevel full > path/file.plist" };
Process p = Runtime.getRuntime.exec(cmd);

Of course, you could also just read the output of your Process instance using Process.getInputStream() and write that into the file you want; thus skip the shell, IO redirection, etc. altogether.

paulsm4

Christian.K is absolutely correct. Here is a complete example:

public class Hello {

  static public void main (String[] args) {
    try {
      String[] cmds = {
        "/bin/sh", "-c", "ls -l *.java | tee tmp.out"};
      Process p = Runtime.getRuntime().exec (cmds);
      p.waitFor ();
      System.out.println ("Done.");
    }
    catch (Exception e) {
      System.out.println ("Err: " + e.getMessage());
    }
  }
}

If you weren't using a pipe (|) or redirect (>), then you'd be OK with String cmd = "ls -l *.java", as in your original command.

If you actually wanted to see any of the output in your Java console window, then you'd ALSO need to call Process.getInputStream().

Here's a good link: Running system commands in Java applications

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!