代码之家  ›  专栏  ›  技术社区  ›  Ahmad Al-Kurdi

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

  •  0
  • Ahmad Al-Kurdi  · 技术社区  · 6 年前

    我得到以下信息 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 回复  |  直到 6 年前
        1
  •  1
  •   daggett    6 年前

    classloader.getResource(..) 收益率 URL

    所以只是申请 getText("UTF-8") 统一资源定位地址 :

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

    或:

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