简体   繁体   中英

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

There is the line Desktop.getDesktop().open(new File("url")) for opening a file that is within my project folder. But once I build the project as a jar, this line no longer opens the file that I want it to, even though it is compressed along with the jar. How can I open the file once it is in the jar file?

Very simple use:

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

This opens it with Excel. And I want that same effect, at least on my computer, when I click the button from the jar file.

You need to extract first the file from your JAR file to a temporary location since the desktop application might not be able to open files inside an archive. Using this theory, this could be a solution you seek

       /*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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM