我正在尝试使用java代码阅读Google SpreadSheet。为此,我下载了client_secret.json文件,并在我的java代码中配置如下:
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;
}
以上代码工作正常。在这里,我将client_secret.json文件放在src / main / resources / path中。
但是现在我想从一些自定义路径中读取client_secret.json,如下所示:
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
new InputStreamReader(SpreadSheetReader.class.getResourceAsStream("D:/test/client_secret.json")));
但是当我改变到某个不同的路径时,我在上面的确切行中面对“NullPointerException”,尽管我给出了正确的绝对路径。
如果有人遇到过类似的问题,请帮帮我吗?
答案 0 :(得分:0)
SpreadSheetReader.class.getResourceAsStream("D:/test/client_secret.json")
- 很可能是导致NPE的原因,因为getResourceAsStream
正在类路径中查找资源(基本上是在JAR内部)。
D:/
绝对不在类路径中,因此我建议您使用FileInputStream
代替:
... new InputStreamReader(new FileInputStream("D:/test/.."));