NullPointerException使用Java库从GCS读取文件

时间:2019-06-25 13:08:20

标签: java google-cloud-platform google-cloud-storage

根据官方文档,我一直在尝试读取存储在GCS中的示例文件,但是到目前为止,我唯一得到的只是一个NullPointerException

InputStream sampleStream() {
    String bucketName = "sample";
    String fileName = "sample";

    log.info("Loading file from GCS [bucket: {}, key: {}]", bucketName, fileName);
    try {
        GcsInputChannel readChannel = gcsService().openReadChannel(new GcsFilename(bucketName, fileName), 0);
        return Channels.newInputStream(readChannel);
    } catch(Exception ex) {
        log.error("Error loading file...", ex);
    }
}

private GcsService gcsService() {
    return GcsServiceFactory
        .createGcsService(new RetryParams.Builder()
            .initialRetryDelayMillis(10).retryMaxAttempts(10)
            .totalRetryPeriodMillis(15000)
            .build()
        );
}

但是仍然一直在重试...

RetryHelper(14.16 ms, 1 attempts, com.google.appengine.tools.cloudstorage.SimpleGcsInputChannelImpl$1@278ef74): Attempt #1 failed [java.io.IOException: java.lang.NullPointerException], sleeping for 9 ms

每当在结果InputStream中调用.read()时,都会引发NullPointerException。

我在某处缺少凭证(或本地.json身份验证文件的路径)还是应该考虑更多因素?

1 个答案:

答案 0 :(得分:0)

代码中的显然是错误的假设,返回空对象,这会导致NPE。 这段代码更加简单明了,我添加了链接:

How to read a file from Google Cloud Storage in Java