title: How to call ghostscript from java with whitespaces in file paths
body: <p>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:</p>
  
  <pre><code>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
  </code></pre>
  
  <p><em>The gs gets replaced by gswin32 on windows, given that ghostscript is in the Path.</em></p>
  
  <p>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. </p>
  
  <p>For launching the command I'm using <code>Runtime.getRuntime().exec(command);</code>, passing one single string. I found the following question <a href="https://stackoverflow.com/questions/1804646/getting-ghostscript-to-take-in-files-with-spaces-in-their-name-like-something-i">getting ghostscript to take in files with spaces in their name (like something in &quot;my documents&quot;)</a> but:</p>
  
  <ul>
  <li>I desired to extend it also for linux;</li>
  <li>I found that double quoting works for me, differently than how it's pointed out there.</li>
  </ul>
  
  <p>I would like to understand this thing once per all: can you help me to do this?</p>
  
  <p>Here follows a summary of my attempts, per SO.</p>
  
  <h2>Windows</h2>
  
  <p>Enclosing file names in double quotes worked for me:</p>
  
  <pre><code>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"
  </code></pre>
  
  <h2>Linux</h2>
  
  <p>Tried to enclose file names in double quotes</p>
  
  <pre><code>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"
  </code></pre>
  
  <p>Tried to escape white space with backslash</p>
  
  <pre><code>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
  </code></pre>
  
  <p>Tried both together</p>
  
  <pre><code>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"
  </code></pre>