簡體   English   中英

如何使用默認應用程序從jar文件中打開文件

[英]How to open a file from within a jar file using the default application

有一行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文件中的按鈕時,至少在我的計算機上,我希望獲得同樣的效果。

您首先需要將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());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM