在我的Android应用程序中,我正在访问Google云存储。我已经生成了私钥 xxxxxxxkey.p12 。我已将我的密钥文件放在assets文件夹中。但是在运行项目时,它没有打开key.p12文件。我已经尝试将它放在assets文件夹之外,仍然没有结果。
httpTransport = AndroidHttp.newCompatibleTransport();
AssetManager am = getAssets();
InputStream inputStream = am.open("xxxxxxxxxxKey.p12");
File file = createFileFromInputStream(inputStream);
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId(xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx@developer.gserviceaccount.com")
.setServiceAccountScopes(Collections.singleton(STORAGE_SCOPE))
.setServiceAccountPrivateKeyFromP12File(file).build();
createFileFromInputStream()
private File createFileFromInputStream(InputStream inputStream) {
try {
File f = new File("download/MyKey.p12");
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项目中也做了同样的事情。有什么不同,是因为android?或者文件位置的路径不正确?
答案 0 :(得分:0)
经过一番努力,我得到了答案,非常感谢你的支持。竖起大拇指!
可以使用 AssetManager 检索文件,我们也可以将其作为原始资源
获取使用AssetManager
AssetManager am = getAssets();
InputStream inputStream = am.open("xxxxxxxxxxKey.p12");
File file = createFileFromInputStream(inputStream);
作为原始资源,将文件放在res目录中的raw文件夹中
InputStream ins = getResources().openRawResource(R.raw.keyfile);
File file = createFileFromInputStream(ins);
在编写输出文件时,您必须指定密钥文件实际所属的位置,在我的情况下我使用的是android,我在内部存储(模拟器/设备)内部创建文件密钥持有者/ KeyFile时强>
private File createFileFromInputStream(InputStream inputStream) {
String path = "";
File file = new File(Environment.getExternalStorageDirectory(),
"KeyHolder/KeyFile/");
if (!file.exists()) {
if (!file.mkdirs())
Log.d("KeyHolder", "Folder not created");
else
Log.d("KeyHolder", "Folder created");
} else
Log.d("KeyHolder", "Folder present");
path = file.getAbsolutePath();
try {
File f = new File(path+"/MyKey");
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
e.printStackTrace();
}
return null;
}
那就是它!