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

98
我该如何在Java中使用默认关联程序打开文件呢?(例如电影文件)

1
如果您正在使用 JavaFX,请前往这里这里 - SedJ601
4个回答

162

1
我尝试使用电影文件时一直出现这个异常,但是使用图像文件(bmp)却可以正常工作: java.io.IOException: Failed to open file:/D:/vidz/2006-04-02.wmv. Error message: The parameter is incorrect. - Frederic Morin
请问你能在问题中提供你的代码吗?另外,你使用的是哪个操作系统和Java版本? - Zach Scrivena
哦,顺便说一下,file.exist()== true。 - Frederic Morin
5
我知道已经过了很长时间,但是问题出在我的电脑上。我的Windows XP默认程序关联不正确,导致其他程序出了问题。自那以后,我尝试用其他电脑,这个方法完全有效!已确认接受! - Frederic Morin
7
补充一下这个老答案;如果打开文件是为了编辑,也可以使用.edit()。有些系统默认的查看和编辑应用程序不同;.open()会打开查看器。 - Jason C
显示剩余3条评论

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);
        }

    }

}

0

SwingHacks有适用于旧版本Java的解决方案。

我认为他们使用了Runtime对象在Windows上执行“start”命令,并且在Mac上有类似的命令。


-10

给你:

File myFile = new File("your any type of file url");
FileOpen.openFile(mContext, myFile);

在包内创建一个不同的类:
// code to open default application present in the handset


public class FileOpen {

    public static void openFile(Context context, File url) throws IOException {
        // Create URI
        File file=url;
        Uri uri = Uri.fromFile(file);

        Intent intent = new Intent(Intent.ACTION_VIEW);
        // Check what kind of file you are trying to open, by comparing the url with extensions.
        // When the if condition is matched, plugin sets the correct intent (mime) type, 
        // so Android knew what application to use to open the file
        if (url.toString().contains(".doc") || url.toString().contains(".docx")) {
            // Word document
            intent.setDataAndType(uri, "application/msword");
        } else if(url.toString().contains(".pdf")) {
            // PDF file
            intent.setDataAndType(uri, "application/pdf");
        } else if(url.toString().contains(".ppt") || url.toString().contains(".pptx")) {
            // Powerpoint file
            intent.setDataAndType(uri, "application/vnd.ms-powerpoint");
        } else if(url.toString().contains(".xls") || url.toString().contains(".xlsx")) {
            // Excel file
            intent.setDataAndType(uri, "application/vnd.ms-excel");
        } else if(url.toString().contains(".zip") || url.toString().contains(".rar")) {
            // WAV audio file
            intent.setDataAndType(uri, "application/x-wav");
        } else if(url.toString().contains(".rtf")) {
            // RTF file
            intent.setDataAndType(uri, "application/rtf");
        } else if(url.toString().contains(".wav") || url.toString().contains(".mp3")) {
            // WAV audio file
            intent.setDataAndType(uri, "audio/x-wav");
        } else if(url.toString().contains(".gif")) {
            // GIF file
            intent.setDataAndType(uri, "image/gif");
        } else if(url.toString().contains(".jpg") || url.toString().contains(".jpeg") || url.toString().contains(".png")) {
            // JPG file
            intent.setDataAndType(uri, "image/jpeg");
        } else if(url.toString().contains(".txt")) {
            // Text file
            intent.setDataAndType(uri, "text/plain");
        } else if(url.toString().contains(".3gp") || url.toString().contains(".mpg") || url.toString().contains(".mpeg") || url.toString().contains(".mpe") || url.toString().contains(".mp4") || url.toString().contains(".avi")) {
            // Video files
            intent.setDataAndType(uri, "video/*");
        } else {
            //if you want you can also define the intent type for any other file

            //additionally use else clause below, to manage other unknown extensions
            //in this case, Android will show all applications installed on the device
            //so you can choose which application to use
            intent.setDataAndType(uri, "*/*");
        }

        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
        context.startActivity(intent);
    }
}

或者您可以像这样更改if条件 - Vaibhav Joshi
如果(url.getPath().endsWith(".jpg") || url.getPath().endsWith(".jpeg")|| url.getPath().endsWith(".png")) { intent.setDataAndType(uri,"image/*"); } - Vaibhav Joshi
2
这仅适用于Android,不是所有平台的解决方案。 - andred
1
作为一名安卓开发者,我认为至少对其他的安卓开发者来说这会很有帮助。 - Vaibhav Joshi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接