private static Credential buildCredentialFromP12(String privateKeyPath,
                                                   Optional<String> fsUri,
                                                   Optional<String> id,
                                                   HttpTransport transport,
                                                   Collection<String> serviceAccountScopes) throws IOException, GeneralSecurityException {
    Preconditions.checkArgument(id.isPresent(), "user id is required.");

    FileSystem fs = getFileSystem(fsUri);
    Path keyPath = getPrivateKey(fs, privateKeyPath);

    final File localCopied = copyToLocal(fs, keyPath);
    localCopied.deleteOnExit();
    try {
      return new GoogleCredential.Builder()
                                 .setTransport(transport)
                                 .setJsonFactory(JSON_FACTORY)
                                 .setServiceAccountId(id.get())
                                 .setServiceAccountPrivateKeyFromP12File(localCopied)
                                 .setServiceAccountScopes(serviceAccountScopes)
                                 .build();
    } finally {
      boolean isDeleted = localCopied.delete();
      if (!isDeleted) {
        throw new RuntimeException(localCopied.getAbsolutePath() + " has not been deleted.");
      }
    }
  }
private static Credential buildCredentialFromP12 ( String privateKeyPath , Optional < String > fsUri , Optional < String > id , HttpTransport transport , Collection < String > serviceAccountScopes ) throws IOException , GeneralSecurityException { Preconditions . checkArgument ( id . isPresent ( ) , "user id is required." ) ; FileSystem fs = getFileSystem ( fsUri ) ; Path keyPath = getPrivateKey ( fs , privateKeyPath ) ; final File localCopied = copyToLocal ( fs , keyPath ) ; localCopied . deleteOnExit ( ) ; try { return new GoogleCredential . Builder ( ) . setTransport ( transport ) . setJsonFactory ( JSON_FACTORY ) . setServiceAccountId ( id . get ( ) ) . setServiceAccountPrivateKeyFromP12File ( localCopied ) . setServiceAccountScopes ( serviceAccountScopes ) . build ( ) ; } finally { boolean isDeleted = localCopied . delete ( ) ; if ( ! isDeleted ) { throw new RuntimeException ( localCopied . getAbsolutePath ( ) + " has not been deleted." ) ; } } }
As Google API only accepts java.io.File for private key, and this method copies private key into local file system.
Once Google credential is instantiated, it deletes copied private key file.

@param privateKeyPath
@param fsUri
@param id
@param transport
@param serviceAccountScopes
@return Credential
@throws IOException
@throws GeneralSecurityException