简体   繁体   中英

Java - How to open a file located in a jar file

I'm using eclipse.
I put a .pdf file in my src folder, i want to open it with the default OS program. The problem is that, if i execute the program with eclipse, i can open it (clicking on a MenuItem) like this :

File memo=new File("src/chap.pdf");
         try {
            Desktop.getDesktop().open(memo);
        } catch (IOException e) {
            e.printStackTrace();
        }

However, after exporting the project to a jar file, this isn't working anymore.
So is there a problem in my code or is there another way to get the file to open when it's in the jar file ?

The src path will not be available after you have exported your program and you should never reference it in any way.

You need to extract the resource from the Jar file and write it to the local disk...

try (InputStream is = getClass().getResourceAsStrea("/chap.pdf")) {
    try (BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(...)) {
        // Write contents like you would any file
    }
} catch (IOException exp) {
    exp.printStackTrace();
}

Then you can use the extracted file with Desktop

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