firas
firas

Reputation: 1503

Java normalize file path for external execution

I have this code:

StringBuilder command = new StringBuilder("ffmpeg -ac 1 -i ");
command.append(videoFile.getPath());
command.append(" ");
command.append(audioFile.getPath());
Process proc = Runtime.getRuntime().exec(command.toString());

The problem is when the file (videoFile | audioFile) have a space character in their path, the process (ffmpeg) fail to execute. My question is how can I fix the path for both Linux and Windows before executing the process ?

Thank you.

Upvotes: 0

Views: 704

Answers (1)

sleske
sleske

Reputation: 83635

Instead of using exec(String), use exec(String[]) (from Runtime). The second form lets you supply all arguments individually, that way Java does not need to parse them further, and will not split on spaces.

Example:

  Process proc = Runtime.getRuntime().exec(
    new String[]{"ffmpeg", "-ac", "1", "-i",videoFile.getPath()), audioFile.getPath()}
  );

You should always use the second form if your arguments may contain spaces, otherwise your command may break.

Upvotes: 3

Related Questions