0

Ok I'm developing in Linux using Eclipse a program that needs to read a text file. The idea is to have the JAR and text file on the same folder. So I'm getting the text file path like this:

Client.class.getClassLoader().getResource("Client.class");

This correctly returns the path and I append the file name and get the below path:

/home/marquinio/workspace/my_project/info.txt

Problem is when I export my project into an executable JAR file. The JAR can't read the file. I double checked and everything looks fine. The only problem I see is that now the path has some "file:" appended at the beginning like this:

file:/home/marquinio/workspace/my_project/info.txt

which is probably why I'm getting a "FileNotFoundException". The JAR and text file are both in the same folder.

Anyone knows how to fix this? Why would Java behave different between Eclipse and executing JAR in command prompt? Is there a replacement to the "...getResource(...)" provided by Java without that "file:"?

NOTE: this JAR should also be compatible in Windows environment. Still need to test it.

Thanks in advance.

3
  • One possibility: pass in a command line parameter when calling the jar that is a path to the text file. Commented Sep 26, 2011 at 3:00
  • 1
    "needs to read a text file" If there is no need to write to the text file, put it in the Jar and get the URL using getResource(String). The URL cannot be used for Desktop.open(File) but there is Desktop.browse(URI) and a number of other ways to display the text file in just a few lines of code. Commented Sep 26, 2011 at 3:03
  • Oops! I just realized that Desktop.browse(URI) will fail for a resource in a Jar. How silly of me. Still, amongst the other ways is JEditorPane.setPage(URL). Drop the JEP in a JScrollPane, set a sensible preferred size for it and show it using a JOptionPane. About 5-10 lines of code. Here is a short example. Commented Sep 26, 2011 at 3:50

1 Answer 1

1

The resource you are referring to is not guaranteed to be a file on the file system. Why not use ClassLoader#getResourceAsStream()? Without looking into the details, my best guess is that the different behavior you are seeing is because a different classloader is being used in each case above.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.