0

I am trying to read Google SpreadSheet using java code. For that I have downloaded the client_secret.json file and configured in my java code as below:

public static Credential authorize() throws IOException {
        // Load client secrets.
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
                new InputStreamReader(SpreadSheetReader.class.getResourceAsStream("/client_secret.json")));

                // Build flow and trigger user authorization request.
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY,
                clientSecrets, SCOPES).setDataStoreFactory(DATA_STORE_FACTORY).setAccessType("offline").build();
        Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver())
                .authorize(service_account);
        System.out.println("Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
        logger.info("Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
        return credential;
    }

Above code is working fine. Here I have placed client_secret.json file in src/main/resources/ path.

But now I want to read client_secret.json from some custom path like below:

GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
                new InputStreamReader(SpreadSheetReader.class.getResourceAsStream("D:/test/client_secret.json")));  

But when I change to some different path I am facing "NullPointerException" in the above exact line though I give correct absolute path.

If anyone has encountered similar issue could you please help me?

user2531569
  • 609
  • 4
  • 18
  • 36

1 Answers1

0

SpreadSheetReader.class.getResourceAsStream("D:/test/client_secret.json") - is most likely what's causing the NPE, since getResourceAsStream is looking for resources in the classpath (inside your JAR, basically).

D:/ is definitely not in the classpath, so I suggest you use a FileInputStream instead:

... new InputStreamReader(new FileInputStream("D:/test/.."));

Cargeh
  • 1,029
  • 9
  • 18
  • Hi. As suggested I tried like this : new InputStreamReader(new FileInputStream("D:/test/client_secret.json"))); But I am facing below error now: Exception in thread "main" com.google.api.client.auth.oauth2.TokenResponseException: 401 Unauthorized. This error is coming from below line in my code: ValueRange response = service.spreadsheets().values().get(spreadsheetId, range).execute(); – user2531569 Apr 18 '18 at 08:17
  • 1
    @user2531569 I'm afraid this is a different question. You asked about NPE, you got an answer regarding the NPE. Authorization issues should be faced in a different question IF you don't figure it out yourself – Cargeh Apr 18 '18 at 08:22
  • 1
    Agree with you. Thanks – user2531569 Apr 18 '18 at 09:04