views:

330

answers:

3

In our application, we are allowing users to open files and directories.

Java 6 provides us with...

java.awt.Desktop.getDesktop().open(file);

which works great. However, since we need to ensure Java 5 compatibility, we also implement a method of opening files by calling the start command in cmd.exe...

String command = "cmd.exe start ...";
Runtime.getRuntime().exec(command);

This is where the problem shows up. It seems that the start command can only handle 8.3 file names, which means that any non-short (8.3) file/directory names cause the start command to fail.

Is there an easy way to generate these short names? Or any other workarounds?

+4  A: 

Try something like this

import java.io.IOException;

class StartExcel {
    public static void main(String args[])
        throws IOException
    {
        String fileName = "c:\\temp\\xls\\test2.xls";
        String[] commands = {"cmd", "/c", "start", "\"DummyTitle\"",fileName};
        Runtime.getRuntime().exec(commands);
    }
}

It's important to pass a dummy title to the Windows start command where there is a possibility that the filename contains a space. It's a feature.

RealHowTo
This did the trick. Thanks!
thedude19
it's a feature... lol
Beau Martínez
A: 

Or you could try:

Runtime.getRuntime().exec(
  new String[] { System.getenv("windir") + "\\system32\\rundll32.exe",
    "shell32.dll,ShellExec_RunDLL", "http://www.stackoverflow.com" });

Source: http://www.rgagnon.com/javadetails/java-0014.html

Peter Smith