【问题标题】:GetResource with google io Files leads to FileNotFoundException for file from jar rootGetResource with google io Files 导致来自 jar 根文件的 FileNotFoundException
【发布时间】:2016-11-23 08:55:30
【问题描述】:

代码

Files.toString(new File(Thread.currentThread().getContextClassLoader().getResource(
    "login_commands.json").getFile()), Charsets.UTF_8)

例外

java.io.FileNotFoundException: file:\C:\application\target.jar!\login_commands.json (The filename, directory name, or volume label syntax is incorrect)

罐子结构

-- 根

  • login_commands.json

代码在 IDE 中运行良好。

如何读取这个文件?

【问题讨论】:

    标签: java exception jar io resources


    【解决方案1】:

    解决方案

    使用

    Thread.currentThread().getContextClassLoader().getResourceAsStream("login_commands.json")
    

    不是

    Thread.currentThread().getContextClassLoader().getResource("login_commands.json").getFile()
    

    为什么?

    当您使用getResource() 时,类加载器会尝试从<JAR_FOLDER>/YOUR_JAR.jar!login_commands.json 获取您的文件,此路径无效,无法创建java.io.File 并抛出FileNotFoundException

    请注意,您的代码可以在 IDE 中运行,因为您的 IDE 有其自己的 类加载器,当您调用 getResourcegetResourceAsStream 时,从 @987654329 获取文件@ 是创建文件的有效路径。

    【讨论】:

      猜你喜欢
      • 2018-10-19
      • 2015-02-26
      • 1970-01-01
      • 2014-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-30
      • 2012-04-28
      相关资源
      最近更新 更多