How do I open a file with the default associated program in Java? (for example a movie file)
How do I open a file with the default associated program in Java? (for example a movie file)
You can use Desktop.getDesktop().open(File file). See the following question for other options: "[Java] How to open user system preffered editor for given file?"
SwingHacks has a solution for older versions of Java.
I think they used the Runtime object to execute the 'start' command on windows and there is a similar command on the mac.
few examples to open files with default program
Example 1 : Runtime.getRuntime().exec("rundll32.exe shell32.dll ShellExec_RunDLL " + fileName);
Example 2 : Runtime.getRuntime().exec("rundll32.exe url.dll FileProtocolHandler " + fileName);
Example 3 : Desktop.getDesktop().open(fileName);
alternative...
Runtime.getRuntime().exec(fileName.toString());
Runtime.getRuntime().exec("cmd.exe /c Start " + fileName);
Runtime.getRuntime().exec("powershell.exe /c Start " + fileName);
Runtime.getRuntime().exec("explorer.exe " + fileName);
Runtime.getRuntime().exec("rundll32.exe SHELL32.DLL,OpenAs_RunDLL " + fileName);
Or....
public static void openFile(int selecType, File fileName) throws Exception {
String[] commandText = null;
if (!fileName.exists()) {
JOptionPane.showMessageDialog(null, "File not found", "Error", 1);
} else {
switch (selecType) {
case 0:
//Default function
break;
case 1:
commandText = new String[]{"rundll32.exe", "shell32.dll", "ShellExec_RunDLL", fileName.getAbsolutePath()};
break;
case 2:
commandText = new String[]{"rundll32.exe", "url.dll", "FileProtocolHandler", fileName.getAbsolutePath()};
break;
case 3:
commandText = new String[]{fileName.toString()};
break;
case 4:
commandText = new String[]{"cmd.exe", "/c", "Start", fileName.getAbsolutePath()};
break;
case 5:
commandText = new String[]{"powershell.exe", "/c", "Start", fileName.getAbsolutePath()};
break;
case 6:
commandText = new String[]{"explorer.exe", fileName.getAbsolutePath()};
break;
case 7:
commandText = new String[]{"rundll32.exe", "shell32.dll", "OpenAs_RunDLL", fileName.getAbsolutePath()}; //File open With
break;
}
if (selecType == 0) {
Desktop.getDesktop().open(fileName);
} else if (selecType < 8) {
Process runFile = new ProcessBuilder(commandText).start();
runFile.waitFor();
} else {
String errorText = "\nChoose a number from 1 to 7\n\nExample : openFile(1,\"" + fileName + "\")\n\n";
System.err.println(errorText);
JOptionPane.showMessageDialog(null, errorText, "Error", 1);
}
}
}