简体   繁体   English

无法在jar文件中的Java中打开文件

[英]File is not opening in java which is inside jar file

I tried to open file form my java application. 我试图从Java应用程序打开文件。 Using following code from 使用以下代码

Open PDF file on fly from Java application 从Java应用程序即时打开PDF文件

Code: 码:

if (Desktop.isDesktopSupported()) {
    try {
        File myFile = new File("/path/to/file.pdf");
        Desktop.getDesktop().open(myFile);
    } catch (IOException ex) {
    // no application registered for PDFs
    }
}

When I use path like : 当我使用像这样的路径时:

"C:\\Users\\kalathoki\\Documents\\NetBeansProjects\\TestJava\\src\\files\\test.pdf" 

it opens. 它打开。 But my file is inside my package 但是我的文件在我的包里

files/test.pdf 

and I used 我用了

files\\test.pdf 

it shows following exception: 它显示以下异常:

Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: The file: \files\test.pdf doesn't exist.

Why? 为什么? Any Idea... I want to include my file inside my jar file that can open from my application whenever user wants. 任何想法...我想将我的文件包含在jar文件中,该文件可以在用户需要时从我的应用程序打开。

Thanks... 谢谢...

getDesktop#open only allows files to be opened from the file system. getDesktop#open仅允许从文件系统打开文件。 One solution is to keep the PDF file locally on the file system and read from there. 一种解决方案是将PDF文件保留在本地文件系统中并从那里读取。 This eliminates extracting the file from the JAR itself so is more efficient. 这消除了从JAR本身提取文件的麻烦,因此效率更高。

Unfortunately, you cannot load a file through Desktop that is contained in the jar. 不幸的是,您无法通过jar中包含的Desktop加载文件。

However, you are not out of options. 但是,您并非没有选择。 A great workaround is to create a temporary file and then open it as detailed here . 一个很好的解决方法是创建一个临时文件,然后按此处所述打开它。

Good luck! 祝好运!

假设test.pdf位于软件包文件中,请尝试以下操作:

File myFile = new File(getClass().getResource("/files/test.pdf").toURI());

This code is working properly please use this to open pdf file within jar file 此代码正常工作,请使用此代码在jar文件中打开pdf文件

    try {
        // TODO add your handling code here:
        String path = jTextField1.getText();
        System.out.println(path);
        Path tempOutput = null;
        String tempFile = "myFile";
        tempOutput = Files.createTempFile(tempFile, ".pdf");
        tempOutput.toFile().deleteOnExit();
        InputStream is = getClass().getResourceAsStream("/JCADG.pdf");
        Files.copy(is,tempOutput,StandardCopyOption.REPLACE_EXISTING);
        if(Desktop.isDesktopSupported())
        {
            Desktop dTop = Desktop.getDesktop();
            if(dTop.isSupported(Desktop.Action.OPEN))
            {
                dTop.open(tempOutput.toFile());
            }
        }
    } catch (IOException ex) {}

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

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