问题
Recently I found myself having to launch the ghostscript command from java, in both linux and windows environments, with whitespaces in input/output filenames. An example of the command follows:
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
The gs gets replaced by gswin32 on windows, given that ghostscript is in the Path.
I quickly realized that I had to escape the file names in some manner, so the first thing I've done was to enclose them between double quotes. This worked on windows, but not on linux: on linux I've tried the double quotes enclosing and also escaping whitespaces with backslashes, but without success.
For launching the command I'm using Runtime.getRuntime().exec(command);
, passing one single string. I found the following question getting ghostscript to take in files with spaces in their name (like something in "my documents") but:
- I desired to extend it also for linux;
- I found that double quoting works for me, differently than how it's pointed out there.
I would like to understand this thing once per all: can you help me to do this?
Here follows a summary of my attempts, per SO.
Windows
Enclosing file names in double quotes worked for me:
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
Tried to enclose file names in double quotes
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"
Tried to escape white space with backslash
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
Tried both together
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:
Why don't you use Runtime.exec(String[] args) which takes multiple arguments ? This variant is designed to avoid you having to escape such arguments. Since the arguments are provided separately there's no space-based interpolation required and thus no confusion.
来源:https://stackoverflow.com/questions/13799686/how-to-call-ghostscript-from-java-with-whitespaces-in-file-paths