[英]Spring: Check if a classpath resource exists before loading
我有一個代碼,我需要檢查類路徑資源是否存在並應用一些操作。
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。 在這種情況下,我們可以做這樣的事情(雖然有點 hacky):
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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.