java - NullPointerException 使用 Java 中的库从 GCS 读取文件

标签 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 身份验证文件的路径),或者我应该考虑更多事情?

最佳答案

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

How to read a file from Google Cloud Storage in Java

关于java - NullPointerException 使用 Java 中的库从 GCS 读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56754851/

相关文章:

python - 如何从谷歌存储云读取数据到谷歌云数据实验室

java - 损坏的 Java 3D 图形

java - ArrayList初始化类型的区别

google-cloud-platform - 未创建 GCP 托管服务帐号(对于 Cloud Asset API)

javascript - 如何将所有请求重定向到特定域名?

python - sys.exit() GCP 云函数

java - 使用 php 和 java 加密内容

java - Gson反序列化具有不同值类型的json

javascript - 谷歌云存储不一致,在可恢复上传完成后 500 毫秒返回 404

python-3.x - Cloud Storage python客户端无法检索存储桶