英文:
Reading sub-directories of a directory in class path resources with Spring Boot
问题
以下是翻译好的部分:
我试图使用给定的代码片段在我的类路径资源中使用Spring Boot读取目录的子目录(目录名称)。
public List<File> getSubdirectories() {
File file = ResourceUtils.getFile("classpath:/database/scripts");
return Arrays.stream(file.listFiles())
.filter(File::isDirectory)
.map(File::getName)
.collect(Collectors.toList());
}
现在,当我们从IDE中运行此代码时,它会正常工作。但是,当我们将此应用程序构建为jar文件并从那里运行时,它会抛出FileNotFoundException。
我尝试过将目录作为类路径资源加载,但没有找到任何解决办法。
我当前使用的是Java 8。所以,我猜大多数Java 7的解决方案都不会起作用。有没有其他方法可以解决这个问题呢?
英文:
I was trying to read sub-directories(names of directories) of a directory in my class path resources using Spring Boot with snippet given below.
public List<File> getSubdirectories() {
File file = ResourceUtils.getFile("classpath:/database/scripts");
return Arrays.stream(file.listFiles()).filter(File::isDirectory).map(File::getFileName)
.collect(Collectors.toList());
}
Now this would work well when we run this code from IDE.
But when we build this app as a jar and runs it from there it throws a FileNotFoundException.
I tried to load the directory as class path resource as well. But didn't find any luck.
I'm currently using Java 8. So most of the Java 7 solutions won't work I guess.
Is there any other way I can resolve this issue?
答案1
得分: 1
根据 Spring 文档,ResourceUtils 应在框架内部使用。
尝试使用 Resource 替代:
@Value("classpath:database/scripts")
Resource directories;
或者,您可以使用资源加载器:
@Autowired
ResourceLoader resourceLoader;
...
public Resource loadDirectories() {
return resourceLoader.getResource(
"classpath:database/scripts");
}
英文:
As per Spring documentation ResourceUtils are to be used internally within the framework
Try using Resource instead:
@Value("classpath:database/scripts")
Resource directories;
Alternatively, you can use resource loader:
@Autowired
ResourceLoader resourceLoader;
...
public Resource loadDirectories() {
return resourceLoader.getResource(
"classpath:database/scripts");
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论