konze konze - 11 months ago 61
Java Question

Open a file from the src directory (Java)

I've written a short documentation for my Java program. When clicking on the menu Help -> Documentation the default PDF reader of the OS should open the


I'm trying to open the PDF which is located in the directory
Desktop.getDesktop().open(new File("doc/documentation.pdf"));

However, Java does not find the file. When I open the icon for the program with
primaryStage.getIcons().add(new Image("icon/icon_512x512.png"));
it works perfectly in

Here you can see layout of my IntelliJ project.

├── de
│   └── myapp
│   ├── model
│ │ └── *.java
│   ├── view
│ │ └── *.java
│ ├── Main.java
│   └── Controller.java
├── doc
│ └── documentation.pdf
└── icon
└── icon_512x512.png

My stack

  • IntelliJ 2016.2

  • Java 1.8.0_77

Answer Source

It works with new Image("icon/icon_512x512.png") because internally it gets is from the context ClassLoader which is not the case of new File("doc/documentation.pdf") that gets it from the user working directory in case of a relative path, so you could simply apply the same logic.

ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
URL resource = contextClassLoader.getResource("doc/documentation.pdf");
Desktop.getDesktop().open(new File(resource.toURI()));