如何在Java中从Google Cloud Storage读取文件

2022-09-04 01:17:13

我想使用Java从Google Cloud存储中读取文件。下面的链接没有帮助,因为我不使用HttpServletRequest和HttpServletResponse。

使用java从谷歌云存储读取文件

有没有其他方法可以完成此操作?我正在编写一个简单的独立程序作为POC


答案 1

实现这一目标的最简单方法是使用Google的google-cloud Java库。下载将如下所示:

String PROJECT_ID = "my-project";
String PATH_TO_JSON_KEY = "/path/to/json/key";
String BUCKET_NAME = "my-bucket";
String OBJECT_NAME = "my-object";

StorageOptions options = StorageOptions.newBuilder()
            .setProjectId(PROJECT_ID)
            .setCredentials(GoogleCredentials.fromStream(
                    new FileInputStream(PATH_TO_JSON_KEY))).build();

Storage storage = options.getService();
Blob blob = storage.get(BUCKET_NAME, OBJECT_NAME);
ReadChannel r = blob.reader();

答案 2

阅读此 GCloud 文档以获取更多信息。

您的代码应该是:

Storage storage = StorageOptions.newBuilder()
            .setProjectId(projectId)
            .setCredentials(GoogleCredentials.fromStream(new FileInputStream(serviceAccountJSON)))
            .build()
            .getService();
Blob blob = storage.get(BUCKET_URL, OBJECT_URL);
String fileContent = new String(blob.getContent());

推荐