如何使用默认关联程序打开文件

新手上路,请多包涵

如何使用 Java 中的默认关联程序打开文件? (例如电影文件)

原文由 Frederic Morin 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 462
2 个回答

使用默认程序打开文件的几个例子

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 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏