I want to attach User Instructions to a Java application, and allow the user to open it from the help menuitem.

I'm not very familiar with classpath variables. If I use an absolute path name everything is fine, such as

File pdfFile = new File("C:/Program Files/MyProgram/UserGuide.pdf");

But I want to package the UserGuide in the jar file (to avoid issues openning it on a Mac or Linux machine, and prevent the user from deleting it etc.).

So I want to access it using

File pdfFile = new File("files/UserGuide.pdf");

where files is a directory in the package where the main method's class is located. But I get an error
java.io.FileNotFoundException: files\UserGuide.pdf (The system cannot find the path specified)

In Eclipse how do I achieve this?

5 Years
Discussion Span
Last Post by hfx642

I haven't tried this (although I have used a similar approach to opening an InputStream to a file in a jar many times). But maybe its worth a try?

File f = new File((getClass().getResource("files/UserGuide.pdf").toURI()));

You'll probably have to catch a URISyntaxException, although there should never be one


Yes I tried that, and it worked when I run the application from within Eclipse. But when I export to a Runnable Jar File and run the jar file it does not work.

Perhaps I am not exporting to a Runnable jar file correctly?

The way you mention is similar to the way I handle images, which works fine. I use

java.net.URL imgURL = MyClass.class.getResource("images/myImage.png");
        if (imgURL != null) {
            return new ImageIcon(imgURL);
        } else {
            System.err.println("Couldn't find file: " + path);
            return null;

But for some reason this works for images in the /images/ folder but not for the pdf file in the /files/ folder?


I think your Your "/"s should be "\"s.
And, you should probably double them. (ie. "files\\UserGuide.pdf")
This SHOULD get you a little further.

This article has been dead for over six months. Start a new discussion instead.
Take the time to help us to help you. Please be thoughtful and detailed and be sure to adhere to our posting rules.