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?

- 15,034
- 31
- 92
- 178
2 Answers
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.

- 525,659
- 79
- 751
- 1,130
-
But I have other text documents in the same folder and they are found using the first command – Bober02 Aug 21 '12 at 13:35
-
Can you describe your directory structure because it works for me? How are these files arranged relative to the class path, or are you not using the class path? – Peter Lawrey Aug 21 '12 at 13:41
-
What do you mean by class path? I have a project in intellij, have a folder called test in which I have a bunch of test java files + a few txt csv files. txt files are found using getResource but csv are not – Bober02 Aug 21 '12 at 13:47
-
getResource *only* finds files from your class path. I use maven in IntelliJ. I suggest not mixing `.java` files with files which are not compiled. When you run you program, do you intend to only load files from your class path or do you want to be able to load files from anywhere? – Peter Lawrey Aug 21 '12 at 13:52
Have you tried getClass().getClassLoader().getResourceAsStream(file)
This in turn returns an inputstream which you can use to access the file

- 23,901
- 30
- 103
- 143