Spring:在加载之前检查类路径资源是否存在



我有一个代码,我需要在其中检查类路径资源是否存在并应用一些操作。

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

问题:如果资源不存在,ResourceUtils.getFile()会引发FileNotFoundException。同时,我不想对代码流使用异常,我想检查资源是否存在。

问:有没有办法使用 Spring 的 API 检查资源是否存在?

为什么我需要用 Spring 来完成这个:因为如果没有 spring,我需要自己选择一个正确的类加载器,这不方便。我需要有一个不同的代码才能让它在单元测试中工作。

您可以使用 ResourceLoader 接口来加载 getResource(),然后使用 Resource.exists() 检查文件是否存在。

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

它已经回答并且很旧,但想到放是有人看到 docker 和 maven 不能使用相同的解决方案,即使 resource.exists() 返回 true。 在这种情况下,我们可以做这样的事情(虽然有点笨拙):

            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();                        
                }
            }

相关内容

最新更新