konze
konze

Reputation: 893

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

Upvotes: 1

Views: 2081

Answers (3)

Chetan S. Choudhary
Chetan S. Choudhary

Reputation: 310

The files from Classpath can be loaded by using ClassLoader's getResourceAsStream Method. So you can try with generating an Input stream object

InputStream is = Controller.class.getClassLoader().getResourceAsStream("doc/documentation.pdf");

And After generating Input Stream you can read it by Java Program.

Upvotes: 1

Nicolas Filotto
Nicolas Filotto

Reputation: 44965

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

Upvotes: 1

Eugene Chipachenko
Eugene Chipachenko

Reputation: 119

3-rd party applications can not access src dir in your application, in case, when your app assemble in jar archive. You should place your file separately from src.

Of course, java find icons, because it's java API. You can access any resources in src folder through follow methods:

URL url = getClass().getResource("/path/in/src");
InputStream is = getClass().getResourceAsStream("/path/in/src");

If your app is NOT assemble in JAR - try provide full path to file like this:

  URL url = getClass().getResource("/path/in/src");
  File file = new File(url.toURI());

Upvotes: 1

Related Questions