I’ve been using the following code to open Office Documents, PDF, etc. on my windows machines using Java and it’s working fine, except for some reason when a filename has embedded it within it multiple contiguous spaces like ‘File[SPACE][SPACE]Test.doc’.
How can I make this work? I’m not averse to canning the whole piece of code… but I’d rather not replace it with a third party library that calls JNI.
public static void openDocument(String path) throws IOException { // Make forward slashes backslashes (for windows) // Double quote any path segments with spaces in them path = path.replace('/', '\\').replaceAll( '\\\\([^\\\\\\\\\']* [^\\\\\\\\\']*)', '\\\\\\\'$1\''); String command = 'C:\\Windows\\System32\\cmd.exe /c start ' + path + ''; Runtime.getRuntime().exec(command); }
EDIT: When I run it with the errant file windows complains about finding the file. But… when I run the command line directly from the command line it runs just fine.
If you are using Java 6 you can just use the open method of java.awt.Desktop to launch the file using the default application for the current platform.