File is not opening in java which is inside jar file

三世轮回 提交于 2019-12-11 17:35:14

问题


I tried to open file form my java application. Using following code from

Open PDF file on fly from Java application

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.

Thanks...


回答1:


getDesktop#open only allows files to be opened from the file system. One solution is to keep the PDF file locally on the file system and read from there. This eliminates extracting the file from the JAR itself so is more efficient.




回答2:


Unfortunately, you cannot load a file through Desktop that is contained in the jar.

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!




回答3:


Assuming test.pdf is in the package files, try this:

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



回答4:


This code is working properly please use this to open pdf file within jar file

    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) {}


来源:https://stackoverflow.com/questions/19010013/file-is-not-opening-in-java-which-is-inside-jar-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!