Twitter Updates

Thursday 15 January 2009

Java exec and Spaces

As part of my latest java project I need to open files in the OS standard program for that type.

<code example>
String command;
try {
  if (System.getProperty("os.name").contains("Mac")){
   command = "open " + newLocation + "";
  }
  if (System.getProperty("os.name").contains("Win")) {
   command = "cmd.exe /c start " + newLocation;
  }
  Process p = Runtime.getRuntime().exec(command);
  int exitCode = p.waitFor();

} catch (IOException e) {
  System.err.println(e.getMessage());
} catch (Exception e) {
  e.printStackTrace();
}
</code example>

However spaces and escape characters are not handled as you would expect. ie if the filename I am trying to open has spaces in it, it will not work.
This bug report better describes the problem with a potential solution.
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6468220

No comments: