Question

I have a unit test package in which I keep a few txt files. These get loaded via getClass().getResource(file); call and it works just fine. I added into the same folder a csv file, and if I supply its name as the parameter i.e. getClass().getResource("csvFile.csv"); I get null... any ideas why?

Was it helpful?

Solution

When you use

 getClass().getResource("csvFile.csv");

it looks relative to the class.

When you use

 getClass().getClassLoader().getResource("csvFile.csv");

it looks in the top level directories of your class path.

I suspect you want the second form.

From Class.getResource(String)

Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:

  • If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.
  • Otherwise, the absolute name is of the following form:

    modified_package_name/name

    Where the modified_package_name is the package name of this object with '/' substituted for '.' ('\u002e').

As you can see the directory translation of the package name of the class is used.


For example, I have a maven project where the code is under src/main/java. My resources directory src/main/resources

I add csvFile.csv to my resources directory which will be copied to my class path.

public class B {
    B() {
        URL resource = getClass().getClassLoader().getResource("csvFile.csv");
        System.out.println("Found "+resource);
    }
    public static void main(String... args) {
        new B();
    }
}

which prints

Found file:/C:/untitled/target/classes/csvFile.csv

This is in the area built by maven from the resources directory.

OTHER TIPS

Have you tried getClass().getClassLoader().getResourceAsStream(file) This in turn returns an inputstream which you can use to access the file

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top