Monday 8 October 2012

Class.getResourceAsStream() VS. ClassLoader.getResourceAsStream()


For Class.getResourceAsStream(String name), if the name parameter doesn't start with a "/", then it's a relative path to the class's package. If the name parameter starts with a "/", then it's an absolute path.

For ClassLoader.getResourceAsStream(String name), the name parameter is always an absolute path, and it can never start with a "/". If it does, the resource is never found.

If the file cannot be found, both methods return null and no exception is thrown.

The following program illustrates the difference.

Project structure











ResourceAsStream.java

public class ResourceAsStream {

    /**
     * @param args
     */
    public static void main(String[] args) {
        String path1 = "a.properties";
        String path2 = "/a.properties";
        String path3 = "test/a.properties";
        String path4 = "/test/a.properties";
  
        System.out.println("Class.getResourceAsStream()");
        InputStream is = ResourceAsStream.class.getResourceAsStream(path1);
        System.out.println(path1 + " " + (is != null));
        is = ResourceAsStream.class.getResourceAsStream(path2);
        System.out.println(path2 + " " + (is != null));
        is = ResourceAsStream.class.getResourceAsStream(path3);
        System.out.println(path3 + " " + (is != null));
        is = ResourceAsStream.class.getResourceAsStream(path4);
        System.out.println(path4 + " " + (is != null));
        System.out.println();
        System.out.println("ClassLoader.getResourceAsStream()");
        is = ResourceAsStream.class.getClassLoader().getResourceAsStream(path1);
        System.out.println(path1 + " " + (is != null));
        is = ResourceAsStream.class.getClassLoader().getResourceAsStream(path2);
        System.out.println(path2 + " " + (is != null));
        is = ResourceAsStream.class.getClassLoader().getResourceAsStream(path3);
        System.out.println(path3 + " " + (is != null));
        is = ResourceAsStream.class.getClassLoader().getResourceAsStream(path4);
        System.out.println(path4 + " " + (is != null));
  
    }

}


Result:

Class.getResourceAsStream()
a.properties true
/a.properties false
test/a.properties false
/test/a.properties true

ClassLoader.getResourceAsStream()
a.properties false
/a.properties false
test/a.properties true
/test/a.properties false


3 comments: