我尝试实现GmailAPI的代码,但代码找不到credentials.jar。我在谷歌默认代码中放置了 file.exists() 验证,然后我在该位置找到了它们。那么为什么我在执行中看到“找不到文件”错误?
这是带有我的文件验证的 Google 默认代码:
private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
//Verify if the directory of credentials exists:
File credentials = new File(CREDENTIALS_FILE_PATH);
if(credentials.exists()){
System.out.print("The credentials directory exists! --> "+credentials.getAbsolutePath());
}
// Load client secrets.
InputStream in = GmailAPI.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
if (in == null) {
throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
}
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
.setAccessType("offline")
.build();
LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
}
这是执行的输出:
The credentials directory exists! --> C:\rfp\GymSoft\Google\credentials.json
Exception in thread "main" java.io.FileNotFoundException: Resource not found: Google/credentials.json
at apoio.GmailAPI.getCredentials(GmailAPI.java:43)
at apoio.GmailAPI.main(GmailAPI.java:61)
C:\rfp\GymSoft\nbproject\build-impl.xml:1340: The following error occurred while executing this line:
C:\rfp\GymSoft\nbproject\build-impl.xml:981: Java returned: 1
BUILD FAILED (total time: 1 second)
请您参考如下方法:
您必须将 credentials.json
文件放入项目的资源文件夹中,然后声明一个常量并在代码中实现它:
private static final String CREDENTIALS_FILE_PATH = "/credentials.json";
InputStream in = GmailAPI.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
默认情况下,GmailAPI 会在此处搜索 credentials.json
文件,除非您设置绝对路径,但为了避免麻烦,最好将其放在资源文件夹中。
您可以查看使用 Java 的快速入门 Gmail API 示例 here 。