Find a related program to open a file using Java

I want to open a file (say, a text document) from a Java application using the appropriate program installed on my computer (in this example, using MS Word or Open Office Writer).

The catch is that I want to wait until this subprocess completes, 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 that it returns the correct executable? Or is there another way to do this?

+2
java process associations runtime execute
source share
5 answers

The correct platform-independent way to open a file using the corresponding Desktop.open() program. Unfortunately, he does not offer any way to interact with the resulting process.

If you want to lose platform independence, 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() 
+2
source share

There is no pure Java way to do this because it is necessarily OS dependent. On the Windows platform, the start command is probably what you are looking for (e.g. start myfile.txt ).

0
source share

There is no universal way to do this on all platforms. On Windows, you can run "start", which will find the correct executable file associated with it. On the poppy you can do "open". As far as I know, on Linux I'm afraid that you will have to manually display your preferred applications.

 String execName = ("cmd /c \"start " + filename + "\""); 
0
source share

You can try to integrate with the Windows registry and other settings for a specific platform, but I believe that the best solution is a simple application that has its own settings.

You can use the classes in package java.util.prefs for this.

0
source share

I get it.

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

If you do this without a start option, it works like a charm (windows only):

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

All Articles