Class Blob
- All Implemented Interfaces:
Serializable
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:
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classClass for specifying blob source options whenBlobmethods are used.static classBuilder forBlob.Nested classes/interfaces inherited from class com.google.cloud.storage.BlobInfo
BlobInfo.CustomerEncryption, BlobInfo.ImmutableEmptyMap<K,V>, BlobInfo.Retention -
Method Summary
Modifier and TypeMethodDescriptionDrop the heldStorageinstance.copyTo(BlobId targetBlob, Blob.BlobSourceOption... options) Sends a copy request for the current blob to the target blob.copyTo(String targetBucket, Blob.BlobSourceOption... options) Sends a copy request for the current blob to the target bucket, preserving its name.copyTo(String targetBucket, String targetBlob, Blob.BlobSourceOption... options) Sends a copy request for the current blob to the target blob.Creates a new ACL entry on this blob.booleandelete(Blob.BlobSourceOption... options) Deletes this blob.booleandeleteAcl(Acl.Entity entity) Deletes the ACL entry for the specified entity on this blob.voiddownloadTo(OutputStream outputStream, Blob.BlobSourceOption... options) Downloads this blob to the given output stream using specified blob read options.voiddownloadTo(Path path) Downloads this blob to the given file path.voiddownloadTo(Path path, Blob.BlobSourceOption... options) Downloads this blob to the given file path using specified blob read options.final booleanReturns true if obj instanceBlob.toPb()metadata representation andBlob.optionsinstance of StorageOptions are both equal.booleanexists(Blob.BlobSourceOption... options) Checks if this blob exists.getAcl(Acl.Entity entity) Returns the ACL entry for the specified entity on this blob ornullif not found.byte[]getContent(Blob.BlobSourceOption... options) Returns this blob's content.Returns the blob'sStorageobject used to issue requests.final inthashCode()listAcls()Lists the ACL entries for this blob.com.google.cloud.ReadChannelreader(Blob.BlobSourceOption... options) Returns aReadChannelobject for reading this blob's content.reload(Blob.BlobSourceOption... options) Fetches the latest blob properties.signUrl(long duration, TimeUnit unit, Storage.SignUrlOption... options) Generates a signed URL for this blob.Returns a builder for the current blob.update(Storage.BlobTargetOption... options) Updates the blob properties.Updates an ACL entry on this blob.com.google.cloud.WriteChannelwriter(Storage.BlobWriteOption... options) Returns aWriteChannelobject for writing to this blob.Methods inherited from class com.google.cloud.storage.BlobInfo
getAcl, getBlobId, getBucket, getCacheControl, getComponentCount, getContentDisposition, getContentEncoding, getContentLanguage, getContentType, getCrc32c, getCrc32cToHexString, getCreateTime, getCreateTimeOffsetDateTime, getCustomerEncryption, getCustomTime, getCustomTimeOffsetDateTime, getDeleteTime, getDeleteTimeOffsetDateTime, getEtag, getEventBasedHold, getGeneratedId, getGeneration, getHardDeleteTime, getKmsKeyName, getMd5, getMd5ToHexString, getMediaLink, getMetadata, getMetageneration, getName, getOwner, getRetention, getRetentionExpirationTime, getRetentionExpirationTimeOffsetDateTime, getSelfLink, getSize, getSoftDeleteTime, getStorageClass, getTemporaryHold, getTimeStorageClassUpdated, getTimeStorageClassUpdatedOffsetDateTime, getUpdateTime, getUpdateTimeOffsetDateTime, isDirectory, newBuilder, newBuilder, newBuilder, newBuilder, newBuilder, toString
-
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- destinationoptions- 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
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
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
Returns this blob's content.Example of reading all bytes of the blob, if its generation matches the
BlobInfo.getGeneration()value, otherwise aStorageExceptionis thrown.byte[] content = blob.getContent(BlobSourceOption.generationMatch());- Parameters:
options- blob read options- Throws:
StorageException- upon failure
-
reload
Fetches the latest blob properties. Returnsnullif the blob no longer exists.optionsparameter can contain the preconditions. For example, the user might want to get the blob properties only if the content has not been updated externally.StorageExceptionwith the code412is 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
Blobobject with latest information ornullif no longer exists. - Throws:
StorageException- upon failure
-
update
Updates the blob properties. Theoptionsparameter contains the preconditions for applying the update. To update the properties calltoBuilder(), set the properties you want to change, build the newBlobinstance, and then callupdate(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
Deletes this blob.Example of deleting the blob, if its generation matches the
BlobInfo.getGeneration()value, otherwise aStorageExceptionis 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:
trueif blob was deleted,falseif 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 idoptions- source blob options- Returns:
- a
CopyWriterobject 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 nameoptions- source blob options- Returns:
- a
CopyWriterobject 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 nametargetBlob- target blob's nameoptions- source blob options- Returns:
- a
CopyWriterobject 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 aReadChannelobject 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 aWriteChannelobject for writing to this blob. By default any md5 and crc32c values in the current blob are ignored unless requested via theBlobWriteOption.md5MatchandBlobWriteOption.crc32cMatchoptions.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 ofServiceAccountSignerwas passed toStorageOptions' builder viasetCredentials(Credentials)or the default credentials are being used and the environment variableGOOGLE_APPLICATION_CREDENTIALSis set or your application is running in App Engine, thensignUrlwill use that credentials to sign the URL. If the credentials passed toStorageOptionsdo not implementServiceAccountSigner(this is the case, for instance, for Compute Engine credentials and Google Cloud SDK credentials) thensignUrlwill throw anIllegalStateExceptionunless an implementation ofServiceAccountSigneris passed using theStorage.SignUrlOption.signWith(ServiceAccountSigner)option.A service account signer is looked for in the following order:
- The signer passed with the option
Storage.SignUrlOption.signWith(ServiceAccountSigner) - The credentials passed to
StorageOptions - 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 inunit. The finer granularity supported is 1 second, finer granularities will be truncatedunit- time unit of thedurationparameteroptions- optional URL signing options- Returns:
- a signed URL for this blob and the specified options
- Throws:
IllegalStateException- ifStorage.SignUrlOption.signWith(ServiceAccountSigner)was not used and no implementation ofServiceAccountSignerwas provided toStorageOptionsIllegalArgumentException- ifSignUrlOption.withMd5()option is used andblobInfo.md5()isnullIllegalArgumentException- ifSignUrlOption.withContentType()option is used andblobInfo.contentType()isnullcom.google.auth.ServiceAccountSigner.SigningException- if the attempt to sign the URL failed- See Also:
- The signer passed with the option
-
getAcl
Returns the ACL entry for the specified entity on this blob ornullif not found.Example of getting the ACL entry for an entity.
Acl acl = blob.getAcl(User.ofAllAuthenticatedUsers());- Throws:
StorageException- upon failure
-
deleteAcl
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:
trueif the ACL was deleted,falseif it was not found- Throws:
StorageException- upon failure
-
createAcl
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
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
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
Returns the blob'sStorageobject used to issue requests. -
toBuilder
Description copied from class:BlobInfoReturns a builder for the current blob. -
equals
Returns true if obj instanceBlob.toPb()metadata representation andBlob.optionsinstance of StorageOptions are both equal. -
hashCode
public final int hashCode() -
asBlobInfo
Drop the heldStorageinstance.- Since:
- 2.14.0
-