How to read a file from Google Cloud Storage in Java
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.
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
The simplest way to accomplish this is to use Google's google-cloud Java library. Downloading will look something like this:
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();
Read this GCloud doc for more info.
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());