I am trying to open a pdf file in my java code. The pdf (named "test.pdf") is saved in packageA. The class (ClassB) trying to open the file is in packageB. I am using the following code:
try {
File pdfFile = new File(ClassB.class.getResource("/packageA/test.pdf").getPath());
if (pdfFile.exists()) {
if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().open(pdfFile);
}
}
else {
//error
}
catch (Exception e) {
//error
}
This works when I run it in eclipse but when I export the program as an executable jar it doesnt work. I get a file not found. I did some research and tried using the following which also didnt work outside eclipse:
ClassLoader cl = this.getClass().getClassLoader();
File pdfFile = new File(cl.getResource("packageA/test.pdf").getFile());