Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/spring-boot/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Spring boot:尝试读取resources文件夹中的目录内容时,从jar读取时会产生FileNotFoundException_Java_Spring Boot_Tomcat_Kotlin - Fatal编程技术网

Java Spring boot:尝试读取resources文件夹中的目录内容时,从jar读取时会产生FileNotFoundException

Java Spring boot:尝试读取resources文件夹中的目录内容时,从jar读取时会产生FileNotFoundException,java,spring-boot,tomcat,kotlin,Java,Spring Boot,Tomcat,Kotlin,所以我有一个问题,与春季开机。基本上,我的想法是在参考资料中有一个名为migrations的目录,它存储需要启动的sql脚本。它在本地机器上运行良好。但是,一旦我将项目上传到服务器,我就会遇到以下错误: Caused by: java.io.FileNotFoundException: class path resource [migrations] cannot be resolved to absolute file path because it does not reside in th

所以我有一个问题,与春季开机。基本上,我的想法是在参考资料中有一个名为
migrations
的目录,它存储需要启动的
sql
脚本。它在本地机器上运行良好。但是,一旦我将项目上传到服务器,我就会遇到以下错误:

Caused by: java.io.FileNotFoundException: class path resource [migrations] cannot be resolved to absolute file path because it does not reside in the file system: 
大量的谷歌搜索帮助我发现了这个问题。它与文件位于
.jar
中有关,当我以
InputStream
的形式读取目录时,正如在其他类似问题中所述,如果我指定该资源的全名,我可以获取特定文件并访问其脚本,如
resourceLoader.getResource(“classpath:migrations/file.sql”)

但是,像这样指定资源的全名并定义所有文件名不是一个选项,因为将来这个文件夹可能会扩展很多,我不想手动编辑代码来将文件添加到运行中。

对于这个问题,是否有任何解决方法可以让我至少从目录中读取文件名,然后逐个访问它们?

我认为如果部署时有一个jar,就没有好的解决方案,除非您使用docker文件复制资源并部署它。getInputStream()始终是从任何地方获取文件的最佳解决方案

也许是这个解决方案,但还没有尝试

ClassLoader cl = this.getClass().getClassLoader(); 
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(cl);
Resource[] resources = resolver.getResources("classpath*:/*.sql") ;
for (Resource resource: resources){
    do your things maybe print the name resource
}

哇,对于一整天的挣扎来说,这是一个很容易解决的问题。谢谢不知何故,使用路径匹配器确实有效,我甚至可以获得
资源[]
。在此之后,我需要做的就是解析
inputStream()
字符串并运行我的查询:)再次感谢!我也很高兴听到;-)