阅读Spring Boot中类路径资源的目录的子目录。

huangapple go评论79阅读模式
英文:

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&lt;File&gt; getSubdirectories() {
	File file = ResourceUtils.getFile(&quot;classpath:/database/scripts&quot;);
	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(&quot;classpath:database/scripts&quot;)
Resource directories;

Alternatively, you can use resource loader:

@Autowired
ResourceLoader resourceLoader;
...
public Resource loadDirectories() {
    return resourceLoader.getResource(
      &quot;classpath:database/scripts&quot;);
}

huangapple
  • 本文由 发表于 2020年4月9日 17:43:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/61118236.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定