Search code examples
javafile-iofileinputstreamfileoutputstream

File is not opening in java which is inside jar file


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...


Solution

  • 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.