Accessing Resources in Java, use of getResource method of Class and ClassLoader, How to access test data in unit tests

Given that:

  • TestABC.java is located at: test/x/y/z/TestABC.java
  • testdata.txt is located at: resources/x/y/z/TestABC/testdata.txt
  • classpath includes resources folder


We are trying to read the testdata.txt from TestABC.java.

We need a location independent way to point to these files. Therefore, we would like to use getResource() method of a Class or ClassLoader.

Here are the correct ways:

1:          this.getClass().getClassLoader().getResource("x/y/z/TestABC/testdata.txt");
2:          this.getClass().getResource("/x/y/z/TestABC/testdata.txt"));
3:          this.getClass().getResource("TestABC/testdata.txt"));




Explanation:

1: works because ClassLoader takes the path as it is (no manipulation) and search in the classpath folders. In this case, it will go to the resources folder and it will find the testdata.txt file in the given path.

2: works because Class.getResource takes the "absolute" path, removes its starting / and then send to ClassLoader. Then it basically becomes the same case with 1.

3: works because Class.getResource takes the "relative" path, prepends the class's package name which is x.y.z and turns that into x/y/z/ and prepends it to the path and pass it to the ClassLoader. Then it again becomes the same case with 1.

Note that ClassLoader do not want absolute paths. So the following would not work this.getClass().getClassLoader().getResource("/x/y/z/TestABC/testdata.txt")).

Comments

Popular posts from this blog

Comparison of equality operators in Ruby: == vs. equal? vs. eql? vs. ===

TCPView