Groovy:当我加载资源文件时,没有这样的文件或目录

时间:2019-01-16 16:41:23

标签: file groovy jar resources

我得到以下Exception

Exception in thread "main" java.io.FileNotFoundException: file:/home/test/untitled2/tool/build/libs/tool-1.0.jar!/datasource/reportQuery.txt (No such file or directory)

当我尝试使用以下命令运行groovy jar时

java -jar tool-1.0.jar

我用来读取资源文件的代码

String loadDataSourceByName(String name) {
    ClassLoader classloader = Thread.currentThread().getContextClassLoader();
    def resource = classloader.getResource("datasource/${name}.txt")
    String fileContents = new File(resource.getFile()).getText('UTF-8')
    fileContents
}

项目结构:

project structure

1 个答案:

答案 0 :(得分:1)

classloader.getResource(..)返回URL

因此只需将getText("UTF-8")应用于URL

String content = classloader.getResource("datasource/${name}.txt")?.getText("UTF-8")

或:

String content = classloader.getResourceAsStream("datasource/${name}.txt")?.getText("UTF-8")