如何使用 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
How to read a file from Google Cloud Storage in Java
提问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
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());