Issue
I wanan check is the resources folder has a xml with the given name. I can do by using File class and then check exists() method, but I was wondering if I can refer to resource file as a Resource and not by File? I tried following but it does not seem to work :
Resource resource = new ClassPathResource("resources/folder/test.xml");//this file is existing
if(resource.exists())
{
System.out.println(" SUCCESS ");
}
else
{
System.out.println(" FAIL . RESOURCE NOT FOUND");
}
Its always going else block when this piece of code is executed.What did I miss?
Solution
The src/main/resources
is the root of the classpath (or the files in there are added to the root. So resources/folder/test.xml
would expect a file in src/main/resources/resources/folder/test.xml
. This is probably not what you want. Remove the resources
part in the file path.
Resource resource = new ClassPathResource("/folder/test.xml");
if(resource.exists()) {
System.out.println(" SUCCESS ");
} else {
System.out.println(" FAIL . RESOURCE NOT FOUND");
}
Should do the trick.
Answered By - M. Deinum
Answer Checked By - Marilyn (JavaFixing Volunteer)