我创建了一个非常简单的项目来测试使用 getClass().getResource('...').getPath()
从 STS、Tomcat 读取目录或文件,并运行 JAR/来自带有嵌入式 Tomcat 的终端的 WAR 文件。
就像我说的,该项目很简单,代码如下:
package org.example
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.CommandLineRunner
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
@SpringBootApplication
class ResourceDemoApplication implements CommandLineRunner {
static void main(String[] args) {
SpringApplication.run ResourceDemoApplication, args
}
@Override
void run(String... arg0) throws Exception {
retrieveDirectory()
}
void retrieveDirectory() {
/*new File(getClass().getResource('/private/folders').getPath()).eachDirRecurse() { dir ->
dir.eachFileMatch(~/.*.txt/) { file ->
println(file.getPath())
}
}*/
println new File(getClass().getResource('/private/folders/').getPath()).isDirectory()
}
}
当此代码在 STS 中运行或将其放入正在运行的 Tomcat 实例中时,它会打印 true
。当我将其作为 java -jar...
运行时,它在终端中返回 false
。我看过无数的例子,但我仍然不明白如何让它正常工作或按预期工作。我知道从 JAR 内部读取文件与访问文件系统不同,但我不确定如何让它工作,无论它是如何部署的。
提前感谢您的帮助!
最佳答案
经过大量研究和深入研究代码,我最终得到了这个解决方案:
package org.example
import org.springframework.boot.CommandLineRunner
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.core.io.FileSystemResource
import org.springframework.core.io.support.PathMatchingResourcePatternResolver
@SpringBootApplication
class ResourceDemoApplication implements CommandLineRunner {
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver()
static void main(String[] args) {
SpringApplication.run ResourceDemoApplication, args
}
@Override
void run(String... arg0) throws Exception {
retrieveDirectory()
}
void retrieveDirectory() {
List<FileSystemResource> files = resolver.findPathMatchingResources('private/folders/**/example.txt')
files.each { file ->
println file.getInputStream().text
}
}
}
使用 groovy,您不需要声明类型等...我这样做是为了这里的文档显示代码中发生的情况。如果您在 Java 中执行此操作,您将需要类似的内容来替换 println file.getInputStream().text
:
InputStream is
BufferedReader br
String fileContents
files.each { file ->
is = file.getInputStream()
br = new BufferedReader(new InputStreamReader(is))
String line
fileContents = ""
while((line = br.readLine()) != null) {
fileContents += line
}
println fileContents
println "************************"
br.close()
}
关于java - JAR/WAR 内的 Spring 资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37570833/