开发者

Find the associated program to open a file using Java

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 findAssociate开发者_开发百科dApplicationPath() method so it returns the correct executable? Or is there another way to do this?


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()


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).


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 + "\"");


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.


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()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜