Don't use File.separator when loading resource files into Java. Even though File.separator
is created to make Java program portable to different platforms, using it to load resource files will just have opposite effect.
I was working on a project written in Java. A simplified structure of project was like this:
1 | |--src |
The program tried to load a properties file when it started.
1 | public class Main { |
When I tested this program in a ubuntu machine, it worked perfectly. However when I copied the same jar and ran it in a windows machine, it broke and showed the following error message:
1 | [ERROR] App configuration META-INF\app.properties is not found. |
I unzipped the jar and did see app.properties
file under META-INF
folder. A ls META\app.properties
command also worked. Then why Java couldn't load that resource file?
After hours of research I found the answer in Java docs of CLassLoader:
ClassLoader
public URL getResource(String name)
Finds the resource with the given name.
...
The name of a resource is a '/'-separated path name that identifies the resource.
It means that when specifying the resource file to load, you have to use the forward slash /
to separate the path. Since in windows the value of File.separator
is backward slash \
, Java won't be able to find the resource file.
In conclusion, to make your Java program portable to windows and some other platforms, you should not use File.separator
when loading resource files. Use /
instead.