Search code examples
google-cloud-storagecloud-storage

Google Cloud storage library to read from Cloudstorage and download to local/on-prem?


I see options to authenticate and read Buckets/Objects from Google cloud. How do i copy the objects directly to my local/on-prem where the below program might run? I see some methods like downloadTo, copyTo for blob but looks like it is to copy/download inside google cloud itself, if i am not wrong. The downloadTo path doesn't allow me to configure a server with the path.

(Note - I am aware of the gsutil command, but I want it programmatically to download files, if possible)

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

Solution

  • downloadTo does download to where you are executing the code.

    import com.google.cloud.storage.*;
    import java.nio.file.Paths;
    //other imports and setup before this
    
    String bucketName = "MY-BUCKET";
    String filename = "MY-FILE.EXTENSION";
    Blob blob = storage.get(bucketName, filename);
    if (blob != null) {
        blob.downloadTo(Paths.get('path/where/you/want/to/save/the/file.extension'));
    }
    

    This code will take the file that's in the bucket, and download it to whatever path you want, wherever you are running it.