0%

Don't Use File.separator When Loading Java Resource Files

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
2
3
4
5
6
7
8
9
10
|--src
|--main
|--java
| |--myproject
| |--app
| |--Main.java
|
|--resources
|--META-INF
|--app.properties

The program tried to load a properties file when it started.

1
2
3
4
5
6
7
8
9
10
11
public class Main {
private static final String APP_CONF = "META-INF" + File.separator + "app.properties";

static {
InputStream in = Main.class.getClassLoader().getResourceAsStream(APP_CONF);
if (in == null) {
System.err.println("[ERROR] App configuration " + APP_CONF + " is not found.");
System.exit(1);
}
}
}

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.