代码
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)
Jar结构
--根
- login_commands.json
- 等等
该代码在 IDE 中运行良好。
如何读取这个文件?
最佳答案
解决方案
使用
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 有其自己的类加载器,当您调用 getResource
时,它会运行。或getResourceAsStream
,从 workspace/test/target/classes/login_commands.json
获取文件这是创建文件的有效路径。
关于java - GetResource 和 google io Files 会导致 jar root 中的文件出现 FileNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38475867/