Skip to content
Advertisement

Spring: Check if a classpath resource exists before loading

I have a code where I need to check if a classpath resource exists and apply some actions.

File file = ResourceUtils.getFile("classpath:my-file.json");
if (file.exists()) {
    // do one thing
} else {
    // do something else
}

Problem: ResourceUtils.getFile() throws FileNotFoundException if the resource doesn’t exist. At the same time I don’t want to use exceptions for code flow and I’d like to check if a resource exists.

Question: Is there any way to check if a resource exists using Spring’s API?

Why I need this to be done with Spring: Because without spring I’d need to pick a correct class loader myself which is not convenient. I’d need to have a different code to make it work in unit tests.

Advertisement

Answer

You can use the ResourceLoader Interface in order to load use getResource(), then use Resource.exists() to check if the file exists or not.

@Autowired
ResourceLoader resourceLoader;  

Resource resource = resourceLoader.getResource("classpath:my-file.json");
if (resource.exists()) {
  // do one thing
} else {
  // do something else
}
Advertisement