Rory Rory - 5 months ago 47
Java Question

How to get the path of src/test/resources directory in JUnit?

I know I can load a file from src/test/resources with:

getClass().getResource("somefile").getFile()


But how can I get the full path to the src/test/resources directory, i.e. I don't want to load a file, I just want to know the path of the directory?

Answer

Try working with the classloader object:

ClassLoader classLoader = getClass().getClassLoader();
        File file = new File(classLoader.getResource("somefile").getFile());
        System.out.println(file.getAbsolutePath());

Edit to explain a bit more: The class loader is responsible for loading in classes and every class has a reference to one, this code is returning a File from the resource structure, and then by calling the getAbsolutePath on the file you are getting the absolute path of that file

Javadoc for ClassLoader: http://docs.oracle.com/javase/7/docs/api/java/lang/ClassLoader.html