簡體   English   中英

默認構造函數無法處理隱式超級構造函數拋出的異常類型 FileNotFoundException。 必須定義一個顯式構造函數

[英]Default constructor cannot handle exception type FileNotFoundException thrown by implicit super constructor. Must define an explicit constructor

我嘗試了FileNotFoundException 並嘗試捕獲但沒有幫助。 我認為問題就在這里

InputStream serviceAccount = new FileInputStream("/src/main/resources/static/FirebaseAdminSDKJava.json");

全類源代碼:

package uz.xose.webapp;

import java.io.FileInputStream;
import java.io.InputStream;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.google.auth.oauth2.GoogleCredentials;
import com.google.cloud.firestore.Firestore;

import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.cloud.FirestoreClient;



@RestController
public class HelloController { 

    InputStream serviceAccount = new FileInputStream("/src/main/resources/static/FirebaseAdminSDKJava.json");

    GoogleCredentials credentials = GoogleCredentials.fromStream(serviceAccount);

    FirebaseOptions options = new FirebaseOptions.Builder()
        .setCredentials(credentials)
        .build();

    FirebaseApp.initializeApp(options);

    Firestore db = FirestoreClient.getFirestore();

     @RequestMapping("/")
     public String index() {
         return "This is the index!\n";
     }

     @RequestMapping("/hello")
     public String index2() {

         return "Hello, World!\n";
     }
}

我正在使用 Spring 框架。

FirebaseAdminSDKJava.json位於:src -> main -> resources -> static -> FirebaseAdminSDKJava.json

“/src/main/resources/static/FirebaseAdminSDKJava.json”是一個相對文件路徑。 根據您的應用程序運行的位置,此文件可能位於也可能不在該位置。 構建和部署后,“src”目錄將不存在,僅在開發中。

相反,從類路徑加載此文件。 請參閱此答案: How to true read text file from classpath in Java

類路徑包括您在資源目錄中的內容。 請試試這個

1. InputStream in = this.getClass().getClassLoader()
                                .getResourceAsStream("FirebaseAdminSDKJava.json");


2 classpath:static/FirebaseAdminSDKJava.json

對於調試, 1. 在調試器模式下啟動 eclipse 或將您的代碼放在 try 塊中,而不是捕獲 FileNotFoundException 捕獲父異常“異常”。

樣品前

try{
   //your code
}catch(Exception ex){
  ex.printStackTrace();
}

printStackTrace() 將向我們展示問題的實際根本原因

希望它對你有用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM