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

时间:2018-07-05 12:15:55

标签: java

Desktop.getDesktop().open(new File("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文件中的按钮时,至少在我的计算机上,我希望有同样的效果。

1 个答案:

答案 0 :(得分:1)

由于桌面应用程序可能无法打开存档中的文件,因此您需要先将文件从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());