如何使用 Java 从 Google Cloud Storage 读取文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44121510/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 07:57:18  来源:igfitidea点击:

How to read a file from Google Cloud Storage in Java

javagoogle-cloud-storage

提问by sreejithpin

I would like to read a file from Google Cloud storage using Java. The below link was not helpful as I dont use HttpServletRequest and HttpServletResponse.

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

Reading in a file from google cloud storage using java

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

Is there any other way by which I can accomplish this? I m writing a simple stand alone program as POC

有没有其他方法可以做到这一点?我正在编写一个简单的独立程序作为 POC

回答by Brandon Yarbrough

The simplest way to accomplish this is to use Google's google-cloudJava library. Downloading will look something like this:

完成此操作的最简单方法是使用 Google 的google-cloudJava 库。下载将如下所示:

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

回答by Anand Mohan

Read this GClouddoc for more info.

阅读此GCloud文档了解更多信息。

Your code should be:

你的代码应该是:

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