[英]read text file in Spring boot
I have created a spring boot application that read a text file normally when I run it as Java Application, but when I want to generated.jar file from it, it show me an error that indicate that this file is not exist我创建了一个 spring 启动应用程序,当我将它作为 Java 应用程序运行时,它可以正常读取文本文件,但是当我想从中生成 .jar 文件时,它显示一个错误,表明该文件不存在
java.io.FileNotFoundException: ./serviceAccountKey.json (No such file or directory)
my method to read the file is我读取文件的方法是
@PostConstruct
public void Initialization() {
FileInputStream serviceAccount;
try {
serviceAccount = new FileInputStream("./serviceAccountKey.json");
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount)).build();
FirebaseApp.initializeApp(options);
} catch (Exception e) {
System.out.println("something went wrong in firebase initialization ...");
System.out.println(e);
}
}
my project structure is shown in this picture我的项目结构如图所示
In spring you have to put your file in src/main/resources
directory and then you can read it using @Value
annotation.在 spring 中,您必须将文件放在
src/main/resources
目录中,然后您可以使用@Value
注释读取它。
class YourClass {
@Value("classpath:serviceAccountKey.json")
private Resource resource;
@PostConstruct
public void Initialization() {
try {
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(resource.getInputStream()))
.build();
FirebaseApp.initializeApp(options);
} catch (Exception e) {
System.out.println("something went wrong in firebase initialization ...");
System.out.println(e);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.