4673_j
4673_j

Reputation: 497

Path not working; using File.separator

I'm using:

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)
    ...

Upvotes: 3

Views: 4820

Answers (3)

D.Kastier
D.Kastier

Reputation: 3015

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.

Upvotes: 3

Fabien Benoit-Koch
Fabien Benoit-Koch

Reputation: 2841

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 \

Upvotes: 1

Maksym Kreshchyshyn
Maksym Kreshchyshyn

Reputation: 354

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

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').

Upvotes: 2

Related Questions