views:

53

answers:

5

I wish to open a file (lets say, a word document) from a Java application using the associated program installed on the computer (in this example, using MS Word or Open Office Writer).

The catch is that I want to wait until this subprocess finishes, which can be done using the waitFor() method in the Process class.

String executable = findAssociatedApplicationPath(); //for example, returns "C:\\Program Files\\Microsoft Office\\Office12\\msword.exe"
Process p = Runtime.getRuntime().exec(executable + " " + filepath);
p.waitFor();

Can someone tell me how to write the findAssociatedApplicationPath() method so it returns the correct executable? Or is there another way to do this?

+1  A: 

The proper platform-independant way to open a file using the associated program is Desktop.open(). Unfortunately, it does not offer any way to interact with the resulting process.

If you're willing to lose platform independance, you can use the start command in cmd.exe:

String fileName = "c:\\tmp\\test.doc";
String[] commands = {"cmd", "/c", "start", "\"Title\"",fileName};
Process p = Runtime.getRuntime().exec(commands);
p.waitFor()
Michael Borgwardt
A: 

There's no pure Java way to do this, because it's necessarily OS-specific. On a Windows platform, the start command is probably what you're looking for (for example, start myfile.txt).

crazyscot
A: 

There is no "universal" way to do this across all platforms. On Windows, you can execute "start", which will find the correct associated executable. On the mac, you can execute "open". On Linux, I'm afraid you'll have to map the preferred applications manually as far as I know.

String execName = ("cmd /c \"start " + filename + "\"");
dt
Linux has just as platform-dependent solutions as Windows, except they vary from installation to installation. Gnome has gnome-open, for example.
Mark Peters
A: 

You can try to mess around with the Windows registry and other platform-specific settings, but I think the best solution is to simply have the application have its own preferences setting.

You may want to use the classes in package java.util.prefs for this.

polygenelubricants
A: 

I have figured it out.

Using the cmd.exe + start.exe combo, the method waitFor() will not wait for the subprocess to end.

If doing it without the start option it works like a charm (windows only though):

Process p = Runtime.getRuntime().exec("cmd /c \"" + filename + "\"");   //extra quotes for filenames with spaces
p.waitFor()
Zurb