如何读取gcs bucket中的文件内容

How to read the content of file in gcs bucket

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

下面是我正在尝试的代码,但我没有得到预期的输出。

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

}
} 

根据您的要求,这应该可行:

Blob blob = storage.get(BUCKET_URL, OBJECT_URL); String fileContent = new String(blob.getContent()); System.out.println(fileContent)

请记住,如果您的文件很大,那么保存在内存中并不是最好的选择。您可能需要重新考虑这是否最适合您。这将完全读取内存中的文件。如果您的应用执行其他操作,那么您很容易达到限制。

查看 this Cloud Storage Client Libraries 了解更多详情。