如何使用 Java 中的默认关联程序打开文件? (例如电影文件)
原文由 Frederic Morin 发布,翻译遵循 CC BY-SA 4.0 许可协议
如何使用 Java 中的默认关联程序打开文件? (例如电影文件)
原文由 Frederic Morin 发布,翻译遵循 CC BY-SA 4.0 许可协议
使用默认程序打开文件的几个例子
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);
或者….
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);
}
}
}
原文由 Hakan ÇELİK 发布,翻译遵循 CC BY-SA 4.0 许可协议
4 回答1.5k 阅读✓ 已解决
4 回答1.3k 阅读✓ 已解决
1 回答2.6k 阅读✓ 已解决
2 回答765 阅读✓ 已解决
2 回答1.8k 阅读
2 回答1.7k 阅读
2 回答1.3k 阅读
您可以使用
Desktop.getDesktop().open(File file)
。有关其他选项,请参阅以下问题:“ [Java] 如何打开给定文件的用户系统首选编辑器? ”