java - 访问 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。
解决方案
由于文件在 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));
推荐阅读
- java - 使用 Spring Security 持久化登录操作
- java - log4j2新objectMessageAsJsonObject问题
- swift - 重新加载 UICollectionView viewForSupplementaryElementOfKind 而不重新加载 cellForItemAt
- react-native - REACT NATIVE:如何从 Stack-Navigator 中的 Tap-navigator 访问屏幕
- git - 独立合并/ git diff --no-index 的 3 路等效项
- javascript - KonvaJS 在圆圈顶部翻转文本
- ruby-on-rails - 在 RoR 中提交之前,如何获取模型方法中的属性值?
- python - AttributeError:类型对象“BST”没有属性“包含”
- ios - 为什么社交分享按钮看起来很糟糕?
- echarts - Echarts 将值与 x 标签类别对齐