views:

330

answers:

3

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.

+5  A: 

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.

Dan Dyer
Works like a charm. Thanks.
Allain Lalonde
A: 

Not sure if this will help you much... I use java 1.5+'s ProcessBuilder to launch external shell scripts in a java program. Basically I do the following: ( although this may not apply because you don't want to capture the commands output; you actually wanna fire up the document - but, maybe this will spark something that you can use )

List<String> command = new ArrayList<String>();
command.add(someExecutable);
command.add(someArguemnt0);
command.add(someArgument1);
command.add(someArgument2);
ProcessBuilder builder = new ProcessBuilder(command);
try {
final Process process = builder.start();
...    
} catch (IOException ioe) {}
Matt Cummings
A: 

The issue may be the "start" command you are using, rather than your file name parsing. For example, this seems to work well on my WinXP machine (using JDK 1.5)

import java.io.IOException;
import java.io.File;

public class test {

    public static void openDocument(String path) throws IOException {
     path = "\"" + path + "\"";
     File f = new File( path );
     String command = "C:\\Windows\\System32\\cmd.exe /c " + f.getPath() + "";
         Runtime.getRuntime().exec(command);          
    }

    public static void main( String[] argv ) {
     test thisApp = new test();
     try {
      thisApp.openDocument( "c:\\so\\My Doc.doc");
     }
     catch( IOException e ) {
      e.printStackTrace();
     }
    }
}
KeithL
Just to confirm you are using C:\\so\\My[space][space]Doc.doc right?
Allain Lalonde