Class Blob

All Implemented Interfaces:
Serializable

@TransportCompatibility({HTTP,GRPC}) public class Blob extends BlobInfo
An object in Google Cloud Storage. A Blob object includes the BlobId instance, the set of properties inherited from the BlobInfo class and the Storage instance. The class provides methods to perform operations on the object. Reading a property value does not issue any RPC calls. The object content is not stored within the Blob instance. Operations that access the content issue one or multiple RPC calls, depending on the content size.

Objects of this class are immutable. Operations that modify the blob like update(com.google.cloud.storage.Storage.BlobTargetOption...) and copyTo(com.google.cloud.storage.BlobId, com.google.cloud.storage.Blob.BlobSourceOption...) return a new object. Any changes to the object in Google Cloud Storage made after creation of the Blob are not visible in the Blob. To get a Blob object with the most recent information use reload(com.google.cloud.storage.Blob.BlobSourceOption...).

Example of getting the content of the object in Google Cloud Storage:


 BlobId blobId = BlobId.of(bucketName, blobName);
 Blob blob = storage.get(blobId);
 long size = blob.getSize(); // no RPC call is required
 byte[] content = blob.getContent(); // one or multiple RPC calls will be issued
 
See Also:
  • Method Details

    • downloadTo

      @TransportCompatibility({HTTP,GRPC}) public void downloadTo(Path path, Blob.BlobSourceOption... options)
      Downloads this blob to the given file path using specified blob read options.
      Parameters:
      path - destination
      options - blob read options
      Throws:
      StorageException - upon failure
      See Also:
    • downloadTo

      @TransportCompatibility({HTTP,GRPC}) public void downloadTo(OutputStream outputStream, Blob.BlobSourceOption... options)
      Downloads this blob to the given output stream using specified blob read options.
      Parameters:
      outputStream -
      options -
      Throws:
      StorageException - upon failure
      See Also:
    • downloadTo

      @TransportCompatibility({HTTP,GRPC}) public void downloadTo(Path path)
      Downloads this blob to the given file path.

      This method is replaced with downloadTo(Path, BlobSourceOption...), but is kept here for binary compatibility with the older versions of the client library.

      Parameters:
      path - destination
      Throws:
      StorageException - upon failure
    • exists

      @TransportCompatibility({HTTP,GRPC}) public boolean exists(Blob.BlobSourceOption... options)
      Checks if this blob exists.

      Example of checking if the blob exists.

      
       boolean exists = blob.exists();
       if (exists) {
         // the blob exists
       } else {
         // the blob was not found
       }
       
      Parameters:
      options - blob read options
      Returns:
      true if this blob exists, false otherwise
      Throws:
      StorageException - upon failure
    • getContent

      @TransportCompatibility({HTTP,GRPC}) public byte[] getContent(Blob.BlobSourceOption... options)
      Returns this blob's content.

      Example of reading all bytes of the blob, if its generation matches the BlobInfo.getGeneration() value, otherwise a StorageException is thrown.

      
       byte[] content = blob.getContent(BlobSourceOption.generationMatch());
       
      Parameters:
      options - blob read options
      Throws:
      StorageException - upon failure
    • reload

      Fetches the latest blob properties. Returns null if the blob no longer exists.

      options parameter can contain the preconditions. For example, the user might want to get the blob properties only if the content has not been updated externally. StorageException with the code 412 is thrown if preconditions fail.

      Example of retrieving the blob's latest information only if the content is not updated externally:

      
       Blob blob = storage.get(BlobId.of(bucketName, blobName));
      
       doSomething();
      
       try {
         blob = blob.reload(Blob.BlobSourceOption.generationMatch());
       } catch (StorageException e) {
         if (e.getCode() == 412) {
           // the content was updated externally
         } else {
           throw e;
         }
       }
       
      Parameters:
      options - preconditions to use on reload, see https://cloud.google.com/storage/docs/json_api/v1/objects/get for more information.
      Returns:
      a Blob object with latest information or null if no longer exists.
      Throws:
      StorageException - upon failure
    • update

      Updates the blob properties. The options parameter contains the preconditions for applying the update. To update the properties call toBuilder(), set the properties you want to change, build the new Blob instance, and then call update(BlobTargetOption...).

      The property update details are described in Storage.update(BlobInfo). Storage.update(BlobInfo, BlobTargetOption...) describes how to specify preconditions.

      Example of updating the content type:

      
       BlobId blobId = BlobId.of(bucketName, blobName);
       Blob blob = storage.get(blobId);
       blob.toBuilder().setContentType("text/plain").build().update();
       
      Parameters:
      options - preconditions to apply the update
      Returns:
      the updated Blob
      Throws:
      StorageException - upon failure
      See Also:
    • delete

      @TransportCompatibility({HTTP,GRPC}) public boolean delete(Blob.BlobSourceOption... options)
      Deletes this blob.

      Example of deleting the blob, if its generation matches the BlobInfo.getGeneration() value, otherwise a StorageException is thrown.

      
       boolean deleted = blob.delete(BlobSourceOption.generationMatch());
       if (deleted) {
         // the blob was deleted
       } else {
         // the blob was not found
       }
       
      Parameters:
      options - blob delete options
      Returns:
      true if blob was deleted, false if it was not found
      Throws:
      StorageException - upon failure
    • copyTo

      @TransportCompatibility({HTTP,GRPC}) public CopyWriter copyTo(BlobId targetBlob, Blob.BlobSourceOption... options)
      Sends a copy request for the current blob to the target blob. Possibly also some of the metadata are copied (e.g. content-type).

      Example of copying the blob to a different bucket with a different name.

      
       String bucketName = "my_unique_bucket";
       String blobName = "copy_blob_name";
       CopyWriter copyWriter = blob.copyTo(BlobId.of(bucketName, blobName));
       Blob copiedBlob = copyWriter.getResult();
       
      Parameters:
      targetBlob - target blob's id
      options - source blob options
      Returns:
      a CopyWriter object that can be used to get information on the newly created blob or to complete the copy if more than one RPC request is needed
      Throws:
      StorageException - upon failure
    • copyTo

      @TransportCompatibility({HTTP,GRPC}) public CopyWriter copyTo(String targetBucket, Blob.BlobSourceOption... options)
      Sends a copy request for the current blob to the target bucket, preserving its name. Possibly copying also some of the metadata (e.g. content-type).

      Example of copying the blob to a different bucket, keeping the original name.

      
       String bucketName = "my_unique_bucket";
       CopyWriter copyWriter = blob.copyTo(bucketName);
       Blob copiedBlob = copyWriter.getResult();
       
      Parameters:
      targetBucket - target bucket's name
      options - source blob options
      Returns:
      a CopyWriter object that can be used to get information on the newly created blob or to complete the copy if more than one RPC request is needed
      Throws:
      StorageException - upon failure
    • copyTo

      @TransportCompatibility({HTTP,GRPC}) public CopyWriter copyTo(String targetBucket, String targetBlob, Blob.BlobSourceOption... options)
      Sends a copy request for the current blob to the target blob. Possibly also some of the metadata are copied (e.g. content-type).

      Example of copying the blob to a different bucket with a different name.

      
       String bucketName = "my_unique_bucket";
       String blobName = "copy_blob_name";
       CopyWriter copyWriter = blob.copyTo(bucketName, blobName);
       Blob copiedBlob = copyWriter.getResult();
       

      Example of moving a blob to a different bucket with a different name.

      
       String destBucket = "my_unique_bucket";
       String destBlob = "move_blob_name";
       CopyWriter copyWriter = blob.copyTo(destBucket, destBlob);
       Blob copiedBlob = copyWriter.getResult();
       boolean deleted = blob.delete();
       
      Parameters:
      targetBucket - target bucket's name
      targetBlob - target blob's name
      options - source blob options
      Returns:
      a CopyWriter object that can be used to get information on the newly created blob or to complete the copy if more than one RPC request is needed
      Throws:
      StorageException - upon failure
    • reader

      @TransportCompatibility({HTTP,GRPC}) public com.google.cloud.ReadChannel reader(Blob.BlobSourceOption... options)
      Returns a ReadChannel object for reading this blob's content.

      Example of reading the blob's content through a reader.

      
       try (ReadChannel reader = blob.reader()) {
         ByteBuffer bytes = ByteBuffer.allocate(64 * 1024);
         while (reader.read(bytes) > 0) {
           bytes.flip();
           // do something with bytes
           bytes.clear();
         }
       }
       

      Example of reading just a portion of the blob's content.

      
       int start = 1;
       int end = 8;
       try (ReadChannel reader = blob.reader()) {
         reader.seek(start);
         ByteBuffer bytes = ByteBuffer.allocate(end - start);
         reader.read(bytes);
         return bytes.array();
       }
       
      Parameters:
      options - blob read options
      Throws:
      StorageException - upon failure
    • writer

      @TransportCompatibility({HTTP,GRPC}) public com.google.cloud.WriteChannel writer(Storage.BlobWriteOption... options)
      Returns a WriteChannel object for writing to this blob. By default any md5 and crc32c values in the current blob are ignored unless requested via the BlobWriteOption.md5Match and BlobWriteOption.crc32cMatch options.

      Example of writing the blob's content through a writer.

      
       byte[] content = "Hello, World!".getBytes(UTF_8);
       try (WriteChannel writer = blob.writer()) {
           writer.write(ByteBuffer.wrap(content, 0, content.length));
       } catch (IOException ex) {
         // handle exception
       }
       blob = blob.reload();
       
      Parameters:
      options - target blob options
      Throws:
      StorageException - upon failure
    • signUrl

      @TransportCompatibility(HTTP) public URL signUrl(long duration, TimeUnit unit, Storage.SignUrlOption... options)
      Generates a signed URL for this blob. If you want to allow access for a fixed amount of time to this blob, you can use this method to generate a URL that is only valid within a certain time period. This is particularly useful if you don't want publicly accessible blobs, but also don't want to require users to explicitly log in. Signing a URL requires a service account signer. If an instance of ServiceAccountSigner was passed to StorageOptions' builder via setCredentials(Credentials) or the default credentials are being used and the environment variable GOOGLE_APPLICATION_CREDENTIALS is set or your application is running in App Engine, then signUrl will use that credentials to sign the URL. If the credentials passed to StorageOptions do not implement ServiceAccountSigner (this is the case, for instance, for Compute Engine credentials and Google Cloud SDK credentials) then signUrl will throw an IllegalStateException unless an implementation of ServiceAccountSigner is passed using the Storage.SignUrlOption.signWith(ServiceAccountSigner) option.

      A service account signer is looked for in the following order:

      1. The signer passed with the option Storage.SignUrlOption.signWith(ServiceAccountSigner)
      2. The credentials passed to StorageOptions
      3. The default credentials, if no credentials were passed to StorageOptions

      Example of creating a signed URL for the blob that is valid for 2 weeks, using the default credentials for signing the URL:

      
       URL signedUrl = blob.signUrl(14, TimeUnit.DAYS);
       

      Example of creating a signed URL for the blob passing the Storage.SignUrlOption.signWith(ServiceAccountSigner) option, that will be used to sign the URL:

      
       String keyPath = "/path/to/key.json";
       URL signedUrl = blob.signUrl(14, TimeUnit.DAYS, SignUrlOption.signWith(
           ServiceAccountCredentials.fromStream(new FileInputStream(keyPath))));
       

      Example of creating a signed URL for a blob generation:

      
       URL signedUrl = blob.signUrl(1, TimeUnit.HOURS,
           SignUrlOption.withQueryParams(ImmutableMap.of("generation", "1576656755290328")));
       
      Parameters:
      duration - time until the signed URL expires, expressed in unit. The finer granularity supported is 1 second, finer granularities will be truncated
      unit - time unit of the duration parameter
      options - optional URL signing options
      Returns:
      a signed URL for this blob and the specified options
      Throws:
      IllegalStateException - if Storage.SignUrlOption.signWith(ServiceAccountSigner) was not used and no implementation of ServiceAccountSigner was provided to StorageOptions
      IllegalArgumentException - if SignUrlOption.withMd5() option is used and blobInfo.md5() is null
      IllegalArgumentException - if SignUrlOption.withContentType() option is used and blobInfo.contentType() is null
      com.google.auth.ServiceAccountSigner.SigningException - if the attempt to sign the URL failed
      See Also:
    • getAcl

      @TransportCompatibility({HTTP,GRPC}) public Acl getAcl(Acl.Entity entity)
      Returns the ACL entry for the specified entity on this blob or null if not found.

      Example of getting the ACL entry for an entity.

      
       Acl acl = blob.getAcl(User.ofAllAuthenticatedUsers());
       
      Throws:
      StorageException - upon failure
    • deleteAcl

      @TransportCompatibility({HTTP,GRPC}) public boolean deleteAcl(Acl.Entity entity)
      Deletes the ACL entry for the specified entity on this blob.

      Example of deleting the ACL entry for an entity.

      
       boolean deleted = blob.deleteAcl(User.ofAllAuthenticatedUsers());
       if (deleted) {
         // the acl entry was deleted
       } else {
         // the acl entry was not found
       }
       
      Returns:
      true if the ACL was deleted, false if it was not found
      Throws:
      StorageException - upon failure
    • createAcl

      @TransportCompatibility({HTTP,GRPC}) public Acl createAcl(Acl acl)
      Creates a new ACL entry on this blob.

      Example of creating a new ACL entry.

      
       Acl acl = blob.createAcl(Acl.of(User.ofAllAuthenticatedUsers(), Acl.Role.READER));
       
      Throws:
      StorageException - upon failure
    • updateAcl

      @TransportCompatibility({HTTP,GRPC}) public Acl updateAcl(Acl acl)
      Updates an ACL entry on this blob.

      Example of updating a new ACL entry.

      
       Acl acl = blob.updateAcl(Acl.of(User.ofAllAuthenticatedUsers(), Acl.Role.OWNER));
       
      Throws:
      StorageException - upon failure
    • listAcls

      @TransportCompatibility({HTTP,GRPC}) public List<Acl> listAcls()
      Lists the ACL entries for this blob.

      Example of listing the ACL entries.

      
       List<Acl> acls = blob.listAcls();
       for (Acl acl : acls) {
         // do something with ACL entry
       }
       
      Throws:
      StorageException - upon failure
    • getStorage

      public Storage getStorage()
      Returns the blob's Storage object used to issue requests.
    • toBuilder

      public Blob.Builder toBuilder()
      Description copied from class: BlobInfo
      Returns a builder for the current blob.
      Overrides:
      toBuilder in class BlobInfo
    • equals

      public final boolean equals(Object obj)
      Returns true if obj instance Blob.toPb() metadata representation and Blob.options instance of StorageOptions are both equal.
      Overrides:
      equals in class BlobInfo
    • hashCode

      public final int hashCode()
      Overrides:
      hashCode in class BlobInfo
    • asBlobInfo

      @BetaApi public BlobInfo asBlobInfo()
      Drop the held Storage instance.
      Since:
      2.14.0 This new api is in preview and is subject to breaking changes.