Sebastian Zeki Sebastian Zeki - 1 year ago 69
Java Question

How to open a file with a specific programme in Desktop

I am using java.awt.Desktop to open a file. I don't have control over the filetype programme associations and I would like to open a file with a specific programme that is non default. How can I do this?

This is my code:

public static void open(File document) throws IOException {
Desktop dt = Desktop.getDesktop();
dt.open(document);
}

Answer Source

If you know the name and location of the program to execute, you can run it directly, and provide it with the filename to open as an argument (after a space):

try {
    Runtime runTime = Runtime.getRuntime();
    // Don't forget that '\' needs to be escaped with another '\'
    Process process = runTime.exec("C:\\Windows\\system32\\notepad.exe" +
                                   " " +    // Separate argument with space
                                   document.getAbsolutePath());
} // try
catch (IOException e) {
    e.printStackTrace();
} // catch