0

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

}
} 
  • What does "... but i'm not getting the expected output" mean? What are you finding? What errors or issues are you actually experiencing? – Kolban Jan 21 '20 at 13:24
  • I actually need to print the content in the file or atleast I need a string varible which contains the data in the file – Chakkirala Chaitanya Jan 22 '20 at 03:43

1 Answers1

1

for your request, this should work:

Blob blob = storage.get(BUCKET_URL, OBJECT_URL); String fileContent = new 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.

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

Joss Baron
  • 1,441
  • 10
  • 13