Marquinio Marquinio - 1 year ago 88
Linux Question

Converting Java URL to valid File path in Linux

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:


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


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:


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.

Answer Source

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.