如何读取gcs存储桶中文件的内容 [英] How to read the content of file in gcs bucket

查看:72
本文介绍了如何读取gcs存储桶中文件的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要打印GCS存储桶中文件中存在的数据.根据我的要求,不应将文件下载到本地系统,而代码应直接从gcs存储桶itselef中读取代码.由于我的文件很大,我不想将文件下载到本地系统.

I want to print the data present in the file in GCS bucket.As per my requirement, file should not be downloaded to local system but the code should directly read the code from gcs bucket itselef.As my file size is huge, i dont want to download the file to local system.

下面是我正在尝试的代码,但未获得预期的输出.

Below is the code which i'm trying but i'm not getting the expected output.

import java.io.*;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.cloud.ReadChannel;
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions; 
import java.io.*;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.cloud.ReadChannel;
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions; 


public class BucketData{

public static void main(String[] args) throws IOException{

String PROJECT_ID = "project_name";
String PATH_TO_JSON_KEY = "path/to/json_key";
System.out.println(PATH_TO_JSON_KEY);
String BUCKET_NAME = "bucket";
String OBJECT_NAME = "abhi.txt";


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();
System.out.println(r);

}
} 

推荐答案

对于您的请求,此方法应该有效:

for your request, this should work:

Blob blob = storage.get(BUCKET_URL,OBJECT_URL);字符串fileContent =新的String(blob.getContent());System.out.println(fileContent)

请记住,如果文件很大,那么保存在内存中并不是最好的选择.您可能想重新考虑一下这是否最适合您.这将完全读取内存中的文件.如果您的应用执行其他操作,则可以轻松达到极限.

Please have in mind that if your files are huge, then, keeping in memory could not be the best. You might want to rethink if this is the best for you. This reads the file fully in memory. If your app performs another actions, then you can reach your limit easily.

查看此Cloud Storage客户端库以获得更多详细信息.

Have a look into this Cloud Storage Client Libraries for more detail.

这篇关于如何读取gcs存储桶中文件的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆