[英]Spring Resource Inside JAR/WAR
我創建了一個非常簡單的項目來測試使用STS,Tomcat中的getClass().getResource('...').getPath()
讀取目錄或文件,並從帶有嵌入式Tomcat的終端運行JAR / 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()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.