Redirection with Runtime.getRuntime().exec() doesn't work

时间秒杀一切 提交于 2019-11-26 20:58:26

The problem is, the redirection character (>) is a shell-based construct, not an executable. So unless you're running this command through something like bash (which you're not), it's going to be interpreted as a literal character argument to your exiftool invocation.

If you want to get this to work, you have two options:

  1. Get bash to do it - pass the whole command line as an argument to bash -c. This might need some heroic escaping, although in your case it looks OK.
  2. Do the redirection yourself within Java. Invoke the command without the redirected output (i.e. everything up to the > sign), then read from the process' outputstream and write all the contents to the appropriate file.

The latter approach sounds like more work initially, but when you consider that you need to always read a Process' output anyway (see the javadocs, second paragraph), it's actually very little extra on top of that. You're simply sending this output to a file instead of throwing it away.

If you have Java 7, it's easier:

Process p = new ProcessBuilder()
    .command("exiftool", "-a", "-u", "-g1", "-j",
             new File("videos", filename).toString())
    .redirectOutput(new File("metadata", filename + ".json"))
    .start();

This falls under "solution 2", but the runtime library takes care of the boilerplate.

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