Search code examples
javapathseparator

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

Solution

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