ProcessBuilder not behaving properly with multiple arguments

When you run it at the command prompt you do not wrap the -l 500 in quotes, so they are treated as two different arguments. Enter this at the command line:

file.exe -i some_source -f "-l 500" some_dest

and I expect you will see the same error message as you see when ProcessBuilder is used incorrectly. The file.exe program must be parsing the command line, searching for strings with a leading - character. When it finds the single string "-l 500" it removes the - and does not recognise l 500 as a valid argument.

An argument to ProcessBuilder is analogous to a quoted argument on the command line.


I ran into the same issue with the ffmpeg command where I have many paramters with values. I ended up creating an ArrayList and the adding each item to the list one by one. Here is an example:

List<String> command = new ArrayList<>();
command.add(ffmpegCommand);
command.add("-re");
command.add("-i");
command.add(videoFile);
command.add("-vcodec");
command.add("libx264");
command.add("-vcodec");
command.add("libx264");
command.add("-vb");
command.add("500000");
command.add("-g");
command.add("60");
command.add("-vprofile");
command.add("main");
command.add("-acodec");
command.add("aac");
command.add("-ab");
command.add("128000");
command.add("-ar");
command.add("48000");
command.add("-ac");
command.add("2");
command.add("-vbsf");
command.add("h264_mp4toannexb");
command.add("-strict");
command.add("experimental");
command.add("-f");
command.add("mpegts");
command.add("udp://127.0.0.1:10000?pkt_size=1316");

ProcessBuilder pb = new ProcessBuilder(command);
pb.redirectErrorStream(true);
Process process;
try {
  process = pb.start();
  process.waitFor();
  if (process.exitValue() == 0) {
    // success
  } else {
    // failure
  }
} catch (IOException | InterruptedException e) {
  // handle exception
}

Where ffmpegCommand is the full path to the command and videoFile is the full path to the video. This is the only way that I was able to get the command to run successfully.