开发者

Java normalize file path for external execution

开发者 https://www.devze.com 2023-02-12 19:14 出处:网络
I have this code: StringBuilder command = new StringBuilder(\"ffmpeg -ac 1 -i \"); command.append(videoFile.getPath());

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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消