0

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 ?

Mohamed Benmahdjoub
  • 1,270
  • 4
  • 19
  • 38
  • 2
    You should recover the file as a resource as shown here: [Reading a resource file from within jar](http://stackoverflow.com/q/20389255/1065197) – Luiggi Mendoza May 25 '15 at 02:36
  • 1
    just make a small check , select the jar file and **unzip** it OR [the official way](https://docs.oracle.com/javase/tutorial/deployment/jar/unpack.html) , that should break .jar into folder hierarchy . **make a check if the .pdf is contained in it** – Srinath Ganesh May 25 '15 at 02:45

1 Answers1

3

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

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366