java.io.FileNotFoundException :/key. p12:打开失败:ENOENT(没有这样的文件或目录)

标签 java android google-api google-bigquery

我正在开发我在 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/

相关文章:

java - 如何使用 Selenium 和 Java 在 https ://www. phptravels.net/website 中提取 HTML5 约束验证的文本?

java - 在Spring Security中从jdbcTemplate检索数据

java - 插入数据库AsyncTask错误

android - 有没有办法在 flutter charts_flutter : ^0. 8.1 中垂直放置标签文本

android - FrameLayout 中的 ImageButton 和 Button 不会更改 z-index

android - 在我自己的项目中包含Android Wheel Kankan项目

api - Google Places 自动完成 API 不返回邮政编码

api - Gmail API : resultSizeEstimate gives odd numbers

java - 在益智游戏中移动图 block

google-api - 使用 OAuth2 和 nodemailer 从我的 gmail 帐户发送电子邮件