Find the full Path of a Resource File in the Classpath

Hardcoding the filesystem location of a file in your tests, can become a maintenance problem.

If the resource file changes location, you’ll have to update and re-compile your code to match the new path.

One way to solve this problem is to add the file to the Classpath and get it as a Resource.

import java.util.Properties;
Properties _prop = new Properties();
public void setUp() throws Exception {
    // Loading properties from your Classpath
    InputStream in = this.getClass().getResourceAsStream("/");
    // Print contents to the Console
    System.out.println("Properties: " + _prop.toString());                

If what you really need is the actual filesystem path, you can resolve it invoking the method .getPath() from the class.

For example, let’s say you are testing an application that was designed to use a system property that references a file in the local system. Put the file in the classpath, store it anywhere in the filesystem and then update the property during the test initialization. This allows you to switch between platforms without having to reconfigure the code with the new location.

public void setUp() throws Exception {
    URL location =  this.getClass().getResource("/certStore");
    String FullPath = location.getPath();
    System.setProperty("", FullPath); 

This entry was posted in Java and tagged , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *