Java – How do I read a resource file from a unit test?

How do I read a resource file from a unit test?… here is a solution to the problem.

How do I read a resource file from a unit test?

I have a pure Java module in my Android project. In that project, I want a unit test that reads from a local JSON file stored in a resource folder. Android Studio changed the icon of the resource folder, so I think it will recognize it as a resource folder.

My way of reading:

String json = Files.lines(Paths.get("file.json"))

Folder structure:

  +app (android)
  +module (java only)
            -the java file

My question is how to read a file?

Update as follows

URL resource1 = getClass().getResource("file.json");
URL resource2 = getClass().getClassLoader().getResource("file.json");
URL resource3 = Thread.currentThread().getContextClassLoader().getResource("file.json");
URL resource4 = ClassLoader.getSystemClassLoader().getResource("file.json");

All of this is empty.
I also copied the json file to resources/same.package.structure, but without success.


You don’t need to do all this complicated things with a classloader. You can access the test/resources directory from the /test/* class.

enter image description here

enter image description here

This is how to deserialize a file using its path using SimpleXML. So the source method parameter here is the path to your resource file

enter image description here

Related Problems and Solutions