首页 > 解决方案 > 访问 jar 中的 json 文件时出现 java.io.FileNotFoundException

问题描述

我正在使用此代码File serviceAccountFile = new File(Main.class.getResource("/serviceAccountKey.json").getFile());访问我的“资源”文件夹中的 json 文件。当我从 intellij 运行它时它工作正常。但是从 jar 运行程序时出现此错误。

java.io.FileNotFoundException: file:\C:\Users\Ashirwada\Documents\IIT\JAVA\POS\target\POS-0.6-jar-with-dependencies.jar!\serviceAccountKey.json (The filename, directory name, or volume label syntax is incorrect)
        at java.base/java.io.FileInputStream.open0(Native Method)
        at java.base/java.io.FileInputStream.open(Unknown Source)
        at java.base/java.io.FileInputStream.<init>(Unknown Source)
        at ashirwada.pos.Firebase.initializeFirebase(Firebase.java:27)
        at ashirwada.pos.Main.init(Main.java:33)
        at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(Unknown Source)
        at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(Unknown Source)
        at java.base/java.lang.Thread.run(Unknown Source)

我的资源文件中有其他文件,例如 fxml 文件和 jpg。他们被检测到并且运行良好。这个 json 文件是唯一给我带来问题的东西。我用winrar打开了Jar,json文件与其余的fxml文件和jpg一起存在。我正在使用 maven 用我需要的依赖项编译我的 jar。

标签: javajsonmaven

解决方案


由于文件在 jar 文件中,系统无法解析文件 C:\Users\Ashirwada\Documents\IIT\JAVA\POS\target\POS-0.6-jar-with-dependencies.jar!\UI\serviceAccountKey.json

您应该将 jar 提取到一个文件夹中并从那里读取 json 文件

或者您可以将文件作为资源读取

InputStream in = etClass().getResourceAsStream("/UI/serviceAccountKey.json");
BufferedReader reader = new BufferedReader(new InputStreamReader(in));

推荐阅读