简体   繁体   中英

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.

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
}

It's been answered and old but thought of putting is someone sees docker and maven cannot use the same solution even the resource.exists() returns true. in that case we can do something like this (it's bit hacky though):

            Resource resource = resourceLoader.getResource("classpath:path/to/file");
            if (resource.exists()) {
                try {
                    // below throws file not found if the app runs in docker
                    resource.getFile()
                } catch (FileNotFoundException e) {
                    // docker uses this
                    InputStream stream = new ClassPathResource("classpath:path/to/file").getInputStream();                        
                }
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM