Pipe or Redirect within Java Command

it’s common knowledge to use Runtime.getRuntime().exec(command) to execute any Unix command or Windows command in a Java application. However, when you try to include the pipe ‘|’ or  redirect ‘>’ in the command to alter any output pattern, most of the time the Java will not interpret your command as expected which will turn out to be an error finally. For example, when I tried to run ffmpeg command to encode any video and would like to capture those outputs into a log file, an error of “Unable to find a suitable output format for ‘>’” will appear.

In order to make Java “understand” out purpose, you cannot directly insert the usual command into the exec() parameter. There is a workaround which will solve the issue.

Construct an array:

String[] commands = {
“/bin/sh”,
“-c”,
YOUR REAL COMMAND HERE
}

and pass the commands as argument to the Runtime.getRuntime().exec(commands). In this way, the Java environment will make a sh (YOU COULD USE BASH) environment to execute your command, which will take the pipe and redirect into consideration.

This entry was posted on Monday, July 12th, 2010 at 7:34 pm and is filed under Ubuntu . You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Be the first to comment! Leave a Reply.

You must be logged in to post a comment.

  • Chinese Version

    • Wanna know me more? And you can read Chinese? Feel free to visit my Chinese site, more life records will be found there and wish you enjoying it.
  • Thanks for support

  • twitter

    facebook

    linkedin

  • Categories