Java 如何使用默认应用程序从jar文件中打开文件

Java 如何使用默认应用程序从jar文件中打开文件,java,Java,有一行Desktop.getDesktop().open(新文件(“url”)用于打开项目文件夹中的文件。但是,一旦我将项目构建为一个jar,这一行就不再打开我想要的文件,即使它是随jar一起压缩的。一旦文件在jar文件中,我如何打开它 非常简单的用法: edit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) {

有一行
Desktop.getDesktop().open(新文件(“url”)
用于打开项目文件夹中的文件。但是,一旦我将项目构建为一个jar,这一行就不再打开我想要的文件,即使它是随jar一起压缩的。一旦文件在jar文件中,我如何打开它

非常简单的用法:

edit.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                Desktop.getDesktop().open(new File("resources\\test.csv"));
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    });

这将使用Excel打开它。当我从jar文件中单击按钮时,至少在我的计算机上,我希望得到相同的效果。

您需要首先将文件从jar文件中提取到临时位置,因为桌面应用程序可能无法打开存档中的文件。运用这一理论,这可能是你寻求的解决方案

       /*You can use this section into your function and import the right packages
        * Then include this bit in the function that you intent to perform what you have described in your question
        */
       //I assume your file is of extention '.ext'
       String inputFile = "path/youtfile.ext";
       Path tempOutput = Files.createTempFile("TempManual", ".ext");
       tempOutput.toFile().deleteOnExit();
       System.out.println("tempOutput: " + tempOutput);
       try (InputStream is = YOURCLASS.class.getClassLoader().getResourceAsStream(inputFile)){
          Files.copy(is, tempOutput, StandardCopyOption.REPLACE_EXISTING);
       }
       Desktop.getDesktop().open(tempOutput.toFile());

粘贴更多代码以显示您计划如何使用文件对象?这会从复制文件的行引发nullpointerexception。我假设您添加了正确的导入,如。。。如导入
java.io.InputStream
导入java.io.File
导入java.nio.file.Files
导入java.nio.file.Path
导入java.nio.file.path
导入java.nio.file.StandardCopyOption
导入java.awt.Desktop