1

最近,我发现自己必须在 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

鉴于 ghostscript 在路径中,gs 在 Windows 上被 gswin32 取代。

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

为了启动我正在使用的命令Runtime.getRuntime().exec(command);,传递一个字符串。我发现以下问题让 ghostscript 接收名称中带有空格的文件(例如“我的文档”中的某些内容),但是:

  • 我也想为 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"
4

1 回答 1

4

为什么不使用带有多个参数的Runtime.exec(String[] args)?此变体旨在避免您不得不逃避此类论点。由于参数是单独提供的,因此不需要基于空间的插值,因此不会造成混淆。

于 2012-12-10T11:07:49.917 回答