konze konze - 3 months ago 15
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

documentation.pdf
.

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

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

Here you can see layout of my IntelliJ project.

src
├── META-INF
├── 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

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()));
Comments