如何使用文件路径中的空格从java调用ghostscript

时间:2012-12-10 11:04:12

标签: java escaping whitespace ghostscript

最近我发现自己不得不在Linux和Windows环境中从java启动ghostscript命令,输入/输出文件名中有空格。该命令的一个示例如下:

gs -q -dNOPAUSE -dBATCH -sDEVICE=pnggray -r300 -sOutputFile=/home/nic/tomcat/6.0.33 with spaces/temp/Thread-11/img-%03d.png /home/nic/tomcat/6.0.33 with spaces/temp/tmpfile.tmp

gs被windows上的gswin32取代,因为ghostscript在路径中。

我很快意识到我必须以某种方式逃避文件名,所以我做的第一件事就是将它们用双引号括起来。这适用于Windows,但不适用于Linux:在Linux上我试过封闭的双引号,并且还使用反斜杠转义空格,但没有成功。

用于启动命令我正在使用Runtime.getRuntime().exec(command);,传递一个字符串。我发现了以下问题getting ghostscript to take in files with spaces in their name (like something in "my documents"),但是:

  • 我也希望将它扩展为linux;
  • 我发现双引号对我有用,与其指出的不同。

我想了解一下这件事:你能帮助我做这件事吗?

以下是我的尝试摘要,按照SO。

用双引号括起文件名对我有用:

gswin32 -q -dNOPAUSE -dBATCH -sDEVICE=pnggray -r300 -sOutputFile="C:\Program Files\tomcat 6.0.33 with spaces\temp\Thread-11\img-%03d.png" "C:\Program Files\tomcat 6.0.33 with spaces\temp\tmpfile.tmp"

的Linux

试图用双引号括起文件名

gs -q -dNOPAUSE -dBATCH -sDEVICE=pnggray -r300 -sOutputFile="/home/nic/tomcat/6.0.33 with spaces/temp/Thread-11/img-%03d.png" "/home/nic/tomcat/6.0.33 with spaces/temp/tmpfile.tmp"

试图用反斜杠

来逃避空白区域
gs -q -dNOPAUSE -dBATCH -sDEVICE=pnggray -r300 -sOutputFile=/home/nic/tomcat/6.0.33\ with\ spaces/temp/Thread-11/img-%03d.png /home/nic/tomcat/6.0.33\ with\ spaces/temp/tmpfile.tmp

一起尝试

gs -q -dNOPAUSE -dBATCH -sDEVICE=pnggray -r300 -sOutputFile="/home/nic/tomcat/6.0.33\ with\ spaces/temp/Thread-11/img-%03d.png" "/home/nic/tomcat/6.0.33\ with\ spaces/temp/tmpfile.tmp"

1 个答案:

答案 0 :(得分:4)

为什么不使用带有多个参数的Runtime.exec(String[] args)?此变体旨在避免您必须转义此类参数。由于参数是单独提供的,因此不需要基于空格的插值,因此不会产生混淆。