Here is a code to download File from Google Cloud Storage:
@Override
public void write(OutputStream outputStream) throws IOException {
try {
LOG.info(path);
InputStream stream = new ByteArrayInputStream(GoogleJsonKey.JSON_KEY.getBytes(StandardCharsets.UTF_8));
StorageOptions options = StorageOptions.newBuilder()
.setProjectId(PROJECT_ID)
.setCredentials(GoogleCredentials.fromStream(stream)).build();
Storage storage = options.getService();
final CountingOutputStream countingOutputStream = new CountingOutputStream(outputStream);
byte[] read = storage.readAllBytes(BlobId.of(BUCKET, path));
countingOutputStream.write(read);
} catch (Exception e) {
e.printStackTrace();
} finally {
outputStream.close();
}
}
This works but the problem here is that it has to buffer all the bytes first before it streams back to the client of this method. This is causing a lot of delays especially when the file stored in the GCS is big.
Is there a way to get the File from GCS and stream it directly to the OutputStream, this OutputStream here btw is for a Servlet.