简体   繁体   中英

Path not working; using File.separator

I'm using:

  • jdk 1.8.0.71
  • IntelliJ 2016.3.2
  • Win7

I was curious why this path is not working:

public static final String ZPL_TEMPLATE =
                    File.separator
                    + "templates"
                    + File.separator
                    + "Template.txt";

yet this one works fine:

public static final String TEMPLATE = "/templates/Template.txt";

Here is where is used (this is in another package):

InputStream is = this.getClass().getResourceAsStream(TEMPLATE);

EDIT: the exception:

...
java.lang.NullPointerException: null
    at java.io.Reader.<init>(Reader.java:78)
    at java.io.InputStreamReader.<init>(InputStreamReader.java:72)
    ...

Becaseuse file separator on Win 7 is '\\' and as it states in doc for

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

If the name begins with a '/' ('\/'), 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 '.' ('\.').

When accessing a internal resource, like you did with getResouceAsStream , the file separator must be / .

I believe that you are in a Windows machine, so the file separator is \\ .

For more information, see How to use file separator when loading resources .

getResourceAsStream expect a resource name as a parameter, not a file path.

Resources names in java are separated by forward slashes / , no matter the file system (Resources names/path represents a path on the classpath, not on the filesystem).

Hence, you can't use the file system seperator to build the resource name. On windows, it will be a backslash \\

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM