如何在JAR Springboot中的FileInputStream中读取资源文件夹的文件
我正在尝试从直接放在资源文件夹中的 json 文件中读取值。我能够成功运行它,在 bootrun & 中没有任何错误。也可以使用下面的代码在 IntelliJ 中成功构建
try (FileInputStream serviceAccountStream=new FileInputStream("src/main/resources/mockData.json");) {
credentials = ServiceAccountCredentials.fromStream(serviceAccountStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
catch (Exception e){
System.out.println("Issue with the credential reader"+e.getMessage());
}
但是,当使用上面的代码创建 JAR 时,我收到异常 fileNotFound
java -jar app-0.0.1-SNAPSHOT-plain.jar
java.io.FileNotFoundException: src\main\resources\mockData.json (The system cannot find the path specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at com.exampleBQ.demoBQ.BQConfig.getBQBean(BQConfig.java:31)
```
Could someone plz help on how to read the file as FileInputStream within Jar
I am trying to read values from a json file which I have placed in my resource folder directly. I am able to run it successfully without any error in bootrun & also build successfully within IntelliJ with the below code
try (FileInputStream serviceAccountStream=new FileInputStream("src/main/resources/mockData.json");) {
credentials = ServiceAccountCredentials.fromStream(serviceAccountStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
catch (Exception e){
System.out.println("Issue with the credential reader"+e.getMessage());
}
However when a JAR is created with the above, I am getting exception as fileNotFound
java -jar app-0.0.1-SNAPSHOT-plain.jar
java.io.FileNotFoundException: src\main\resources\mockData.json (The system cannot find the path specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at com.exampleBQ.demoBQ.BQConfig.getBQBean(BQConfig.java:31)
```
Could someone plz help on how to read the file as FileInputStream within Jar
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您使用 Springboot 时,您可以使用 Resource 抽象
尝试这样做:-
As you are using Springboot you can use Resource abstraction
Try doing this:-