Search code examples
javapathdirectoryembedded-resourcelaunch4j

Unable to reach resources folder when compiling from .jar to .exe using Launch4j


I made a small Java program for academic purposes, its main focus is to read some .txt files and present the information to the user. These files are present in the resources folder, under the src folder. The program runs as intended when launched from Eclipse. Using the Launch4j app I was able to successfully create an exe which runs fine and does what's intended, up until I try to read the .txt files I have in the resources folder, which appears not to be able to reach.

I'm guessing that when I launch the exe the run time path would change to where the exe was created, so I created the program in a desktop folder and specified this path in the program, but that doesn't seem to solve the situation.

As an alternative, I moved the .txt files out of the program and once again created the exe in a desktop folder with said .txt files, linked the program to this path and once again it didn't work.

The command used to get the .txt files is:

Files.readAllLines(Paths.get(doc)).get(line)

And doc is simply the path to the intended .txt file.

It's worth noting that I have no previous experience in Java and throughout the development of the program I tried my best to use commands I'd fully understand and to keep it as simple as possible. I hope the solution can be along these lines! I'm very confident this must be a rookie mistake, but I can't seem to find the solution to this specific problem anywhere.


Solution

  • The paths to files in Eclipse are different than the paths to files in an .exe or JAR file.

    I will let this other user explain it because I am lazy :p

    Rather than trying to address the resource as a File just ask the ClassLoader to return an InputStream for the resource instead via getResourceAsStream:

    InputStream in = getClass().getResourceAsStream("/file.txt"); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); As long as the file.txt resource is available on the classpath then this approach will work the same way regardless of whether the file.txt resource is in a classes/ directory or inside a jar.

    The URI is not hierarchical occurs because the URI for a resource within a jar file is going to look something like this: file:/example.jar!/file.txt. You cannot read the entries within a jar (a zip file) like it was a plain old File.

    This is explained well by the answers to:

    How do I read a resource file from a Java jar file?

    Java Jar file: use resource errors: URI is not hierarchical

    The original post is here, all credit to its author.

    Fixing your URL should let you read from that file when you are using the .exe.

    EDITED FOR CORRECTION. Thanks @VGR (see comments) for correcting my mistake.