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



我正在开发一个应用程序,在该应用程序中我使用了android应用程序中的bigquery。我已经在API控制台上创建了一个项目。

我已经将p12文件放在应用程序的assets文件夹中,并且在代码中有正确的路径,但我得到了一个错误java.io.FileNotFoundException: /key.p12: open failed: ENOENT (No such file or directory)

请帮助我需要做什么改变来解决它。

    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();
    }

这是从资产读取文件的正确方法:

    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();
    }

从InputStream 创建文件

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;
}

本教程:http://examples.javacodegeeks.com/java-basics/exceptions/java-io-filenotfoundexception-how-to-solve-file-not-found-exception/举例说明如何解决"找不到文件"异常。基本上,当您遇到上述错误时(没有这样的文件或目录);您需要确保指定的"file:key.p12在您的情况下"是正确的,并且引用了文件本身
你能试着指定指向.p12键的整个路径吗?例如:(新文件("c:/key.p12");)

您可以使用AssetManager,还可以选择将密钥文件放入原始文件夹并从中获取。

既然你使用的是安卓系统,我希望这个答案对有帮助

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

祝你今天过得愉快

最新更新