Home > Software design >  read text file in Spring boot
read text file in Spring boot

Time:02-24

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

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

enter image description here

CodePudding user response:

In spring you have to put your file in src/main/resources directory and then you can read it using @Value annotation.

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);
        }

    } 
}

CodePudding user response:

By default maven will include in the jar, the resource files located under src/main/resources only. So the file serviceAccountKey.json should be moved there.

  • Related