How to resolve class path resource cannot be opened because it does not exist exception when trying to read file from classpath with java
Purpose
In this post, I will demonstrate how to resolve the class path resource cannot be opened because it does not exist
problem when using Java to load a file from the classpath.
The directory structure is as follows:
The code we are using to load the test1.txt
is as follows:
Environment
- Spring Boot 2+
- Java 8+
The Solution
We should place the file in the correct location:
As you can see, the file testfiles/test1.txt
should be placed in the ./resources
directory, either src/main/resources
or src/test/resources
.
Then run the following code:
We get this result:
Why Did This Work?
As shown in the code, we are using ClassPathResource
to load the resource file from the classpath. Let’s look at the details of this class:
public class ClassPathResource extends AbstractFileResolvingResource
Resource implementation for class path resources. Uses either a given ClassLoader or a given Class for loading resources.
Supports resolution as java.io.File if the class path resource resides in the file system, but not for resources in a JAR. Always supports resolution as URL.
So the leading slash is not required, so the following line would work too:
Summary
In this post, I demonstrated how to resolve the FileNotFoundException
when using Java to load a file from the classpath. The key point is to place the file in the correct directory. By ensuring the file is in the resources
directory and using the correct path in the code, you can successfully load the file.
Final Words + More Resources
My intention with this article was to help others who might be considering solving such a problem. So I hope that’s been the case here. If you still have any questions, don’t hesitate to ask me by email: Email me
Here are also the most important links from this article along with some further resources that will help you in this scope:
Oh, and if you found these resources useful, don’t forget to support me by starring the repo on GitHub!