繁体   English   中英

JAR / WAR中的Spring资源

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM