简体   繁体   English

Java-如何打开jar文件中的文件

[英]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. 我将.pdf文件放在src文件夹中,我想使用默认的OS程序打开它。 The problem is that, if i execute the program with eclipse, i can open it (clicking on a MenuItem) like this : 问题是,如果我用Eclipse执行程序,则可以像下面这样打开它(单击MenuItem):

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. 但是,将项目导出到jar文件后,此方法不再起作用。
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 ? 那么我的代码中是否有问题,或者还有其他方法可以将文件放在jar文件中打开?

The src path will not be available after you have exported your program and you should never reference it in any way. 导出程序后, src路径将不可用,并且绝对不应以任何方式引用它。

You need to extract the resource from the Jar file and write it to the local disk... 您需要从Jar文件中提取资源并将其写入本地磁盘...

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 然后,您可以将提取的文件与Desktop

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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