我得到以下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
}
项目结构:
答案 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")