我正在开发我在 android 应用程序中使用 bigquery
的应用程序。我在 API 控制台上创建了一个项目。
我已将 p12 文件放在应用程序的 Assets 文件夹中,并且在代码中具有正确的路径,但我收到错误 java.io.FileNotFoundException:/key.p12: open failed: ENOENT (没有这样的文件或目录)
。
请帮助我需要做哪些更改来解决它。
try {
credential = new GoogleCredential.Builder().setTransport(TRANSPORT)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountScopes(SCOPES)
.setServiceAccountId("xxxxxxxxxxxxxxxx@developer.gserviceaccount.com")
.setServiceAccountPrivateKeyFromP12File(new File("key.p12"))
.build();
} catch (GeneralSecurityException | IOException e1) {
e1.printStackTrace();
}
最佳答案
这是从 Assets 中读取文件的正确方法:
try {
AssetManager am = getAssets();
InputStream inputStream = am.open("key.p12");
File file = createFileFromInputStream(inputStream);
credential = new GoogleCredential.Builder().setTransport(TRANSPORT)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountScopes(SCOPES)
.setServiceAccountId("xxxxxxxxxxxxxxxx@developer.gserviceaccount.com")
.setServiceAccountPrivateKeyFromP12File(file )
.build();
} catch (GeneralSecurityException | IOException e1) {
e1.printStackTrace();
}
从输入流创建文件
private File createFileFromInputStream(InputStream inputStream) {
try{
File f = new File(my_file_name);
OutputStream outputStream = new FileOutputStream(f);
byte buffer[] = new byte[1024];
int length = 0;
while((length=inputStream.read(buffer)) > 0) {
outputStream.write(buffer,0,length);
}
outputStream.close();
inputStream.close();
return f;
}catch (IOException e) {
//Logging exception
}
return null;
}
关于java.io.FileNotFoundException :/key. p12:打开失败:ENOENT(没有这样的文件或目录),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29340571/