2

Can someone explain why Java does not find resource if using File.separator in the String for search path in getResourceAsStream(String name)? I have this code:

private final String RESOURCE_PATH = File.separator + "dir" + File.separator;
private final String SAME_PATH_HARDCODED = "/dir/";

public void findResource(String fileName) {
    InputStream file1 = ThisClass.class
            .getResourceAsStream(RESOURCE_PATH + fileName);  // returns null

    InputStream file2 = ThisClass.class
            .getResourceAsStream(SAME_PATH_HARDCODED + fileName);  // returns file
}

I have found out, that File.separator used Backslashes instead of Slashes. But I hoped that File.separator is more flexible. In this case, it isnt. And I want to know, why. Thanks alot.

LeckerMaedschen
  • 161
  • 2
  • 12

1 Answers1

0

Because when you pass \\ separator to getResourceAsStream() method it interprets path to your dir in another way, added package name before dir actually.

Class javadoc

Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:

If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.
Otherwise, the absolute name is of the following form:

    modified_package_name/name 

Where the modified_package_name is the package name of this object with '/' substituted for '.' ('\u002e').

Your File.separator returns different result for unix and windows machines. If you use mack or unix in this case your code will works but in win machine fails.

File javadoc

public static final char separatorChar

The system-dependent default name-separator character. This field is initialized to contain the first character of the value of the system property file.separator. On UNIX systems the value of this field is '/'; on Microsoft Windows systems it is '\'.

fxrbfg
  • 1,756
  • 1
  • 11
  • 17