无法在运行可执行JAR文件时找到文件。

huangapple 未分类评论42阅读模式
英文:

Unable to locate a file while running an executable JAR file

问题

我创建了一个简单的JAVA项目,它访问一个名为config.json的内部文件,并将内容写入一个名为output.txt的文件。
因为我不想向主类传递参数,所以我将我的config.json添加到了资源文件夹中。

我可以在Eclipse中运行该应用程序而无任何问题。
this.getClass().getClassLoader().getResource("resource/config.json")this.getClass().getResource("/resource/config.json") 都可以从路径 C:/Users/divya_raibagkar/workspace/TestProject/**bin**/resource/config.json 定位到该文件。
但是,当我将其导出为JAR文件并尝试使用命令提示符执行 java -jar D:/Test.jar 时,我会收到以下错误:

返回的文件路径:resource/config.json
加载JSON配置文件:
java.io.FileNotFoundException: resource\config.json(系统找不到指定的路径)

Java项目结构:
无法在运行可执行JAR文件时找到文件。

非常感谢您提供解决此问题的任何线索。
谢谢。

英文:

I have created a simple JAVA project, which accesses an internal file called config.json and writes content to a file output.txt.
As I did not want to send arguments to the main class, I added my config.json to the resource folder.

I am able to run the application in Eclipse without any issue.
Both this.getClass().getClassLoader().getResource("resource/config.json") and this.getClass().getResource("/resource/config.json") are able to locate the file from the path C:/Users/divya_raibagkar/workspace/TestProject/**bin**/resource/config.json
But when I export it to JAR and try to execute from command prompt using java -jar D:/Test.jar, I get the following error:

Returned file path: resource/config.json
Loading JSON config file:
java.io.FileNotFoundException: resource\config.json (The system cannot find the path specified)

Java Project Structure:
无法在运行可执行JAR文件时找到文件。

Any lead to resolve this issue is highly appreciated.
Thank you.

huangapple
  • 本文由 发表于 2020年7月25日 01:18:05
  • 转载请务必保留本文链接:https://java.coder-hub.com/63078465.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定