@TransportCompatibility(value={HTTP,GRPC}) public class Blob extends BlobInfo
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
Modifier and Type | Class and Description |
---|---|
static class |
Blob.BlobSourceOption
Class for specifying blob source options when
Blob methods are used. |
static class |
Blob.Builder
Builder for
Blob . |
BlobInfo.CustomerEncryption, BlobInfo.ImmutableEmptyMap<K,V>
Modifier and Type | Method and Description |
---|---|
BlobInfo |
asBlobInfo()
Drop the held
Storage instance. |
CopyWriter |
copyTo(BlobId targetBlob,
Blob.BlobSourceOption... options)
Sends a copy request for the current blob to the target blob.
|
CopyWriter |
copyTo(String targetBucket,
Blob.BlobSourceOption... options)
Sends a copy request for the current blob to the target bucket, preserving its name.
|
CopyWriter |
copyTo(String targetBucket,
String targetBlob,
Blob.BlobSourceOption... options)
Sends a copy request for the current blob to the target blob.
|
Acl |
createAcl(Acl acl)
Creates a new ACL entry on this blob.
|
boolean |
delete(Blob.BlobSourceOption... options)
Deletes this blob.
|
boolean |
deleteAcl(Acl.Entity entity)
Deletes the ACL entry for the specified entity on this blob.
|
void |
downloadTo(OutputStream outputStream,
Blob.BlobSourceOption... options)
Downloads this blob to the given output stream using specified blob read options.
|
void |
downloadTo(Path path)
Downloads this blob to the given file path.
|
void |
downloadTo(Path path,
Blob.BlobSourceOption... options)
Downloads this blob to the given file path using specified blob read options.
|
boolean |
equals(Object obj)
Returns true if obj instance
Blob.toPb() metadata representation and Blob.options instance of StorageOptions are both equal. |
boolean |
exists(Blob.BlobSourceOption... options)
Checks if this blob exists.
|
Acl |
getAcl(Acl.Entity entity)
Returns the ACL entry for the specified entity on this blob or
null if not found. |
byte[] |
getContent(Blob.BlobSourceOption... options)
Returns this blob's content.
|
Storage |
getStorage()
Returns the blob's
Storage object used to issue requests. |
int |
hashCode() |
List<Acl> |
listAcls()
Lists the ACL entries for this blob.
|
com.google.cloud.ReadChannel |
reader(Blob.BlobSourceOption... options)
Returns a
ReadChannel object for reading this blob's content. |
Blob |
reload(Blob.BlobSourceOption... options)
Fetches the latest blob properties.
|
URL |
signUrl(long duration,
TimeUnit unit,
Storage.SignUrlOption... options)
Generates a signed URL for this blob.
|
Blob.Builder |
toBuilder()
Returns a builder for the current blob.
|
Blob |
update(Storage.BlobTargetOption... options)
Updates the blob properties.
|
Acl |
updateAcl(Acl acl)
Updates an ACL entry on this blob.
|
com.google.cloud.WriteChannel |
writer(Storage.BlobWriteOption... options)
Returns a
WriteChannel object for writing to this blob. |
getAcl, getBlobId, getBucket, getCacheControl, getComponentCount, getContentDisposition, getContentEncoding, getContentLanguage, getContentType, getCrc32c, getCrc32cToHexString, getCreateTime, getCreateTimeOffsetDateTime, getCustomerEncryption, getCustomTime, getCustomTimeOffsetDateTime, getDeleteTime, getDeleteTimeOffsetDateTime, getEtag, getEventBasedHold, getGeneratedId, getGeneration, getKmsKeyName, getMd5, getMd5ToHexString, getMediaLink, getMetadata, getMetageneration, getName, getOwner, getRetentionExpirationTime, getRetentionExpirationTimeOffsetDateTime, getSelfLink, getSize, getStorageClass, getTemporaryHold, getTimeStorageClassUpdated, getTimeStorageClassUpdatedOffsetDateTime, getUpdateTime, getUpdateTimeOffsetDateTime, isDirectory, newBuilder, newBuilder, newBuilder, newBuilder, newBuilder, toString
@TransportCompatibility(value={HTTP,GRPC}) public void downloadTo(Path path, Blob.BlobSourceOption... options)
path
- destinationoptions
- blob read optionsStorageException
- upon failureStorage.downloadTo(BlobId, Path, Storage.BlobSourceOption...)
@TransportCompatibility(value={HTTP,GRPC}) public void downloadTo(OutputStream outputStream, Blob.BlobSourceOption... options)
outputStream
- options
- StorageException
- upon failureStorage.downloadTo(BlobId, OutputStream, Storage.BlobSourceOption...)
@TransportCompatibility(value={HTTP,GRPC}) public void downloadTo(Path path)
This method is replaced with downloadTo(Path, BlobSourceOption...)
, but is kept
here for binary compatibility with the older versions of the client library.
path
- destinationStorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) public boolean exists(Blob.BlobSourceOption... options)
Example of checking if the blob exists.
boolean exists = blob.exists();
if (exists) {
// the blob exists
} else {
// the blob was not found
}
options
- blob read optionsStorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) public byte[] getContent(Blob.BlobSourceOption... options)
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());
options
- blob read optionsStorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) public Blob reload(Blob.BlobSourceOption... options)
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;
}
}
options
- preconditions to use on reload, see https://cloud.google.com/storage/docs/json_api/v1/objects/get
for more information.Blob
object with latest information or null
if no longer exists.StorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) public Blob update(Storage.BlobTargetOption... options)
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();
options
- preconditions to apply the updateBlob
StorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) public boolean delete(Blob.BlobSourceOption... options)
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
}
options
- blob delete optionstrue
if blob was deleted, false
if it was not foundStorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) public CopyWriter copyTo(BlobId targetBlob, Blob.BlobSourceOption... options)
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();
targetBlob
- target blob's idoptions
- source blob optionsCopyWriter
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 neededStorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) public CopyWriter copyTo(String targetBucket, Blob.BlobSourceOption... options)
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();
targetBucket
- target bucket's nameoptions
- source blob optionsCopyWriter
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 neededStorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) public CopyWriter copyTo(String targetBucket, String targetBlob, Blob.BlobSourceOption... options)
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();
targetBucket
- target bucket's nametargetBlob
- target blob's nameoptions
- source blob optionsCopyWriter
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 neededStorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) public com.google.cloud.ReadChannel reader(Blob.BlobSourceOption... options)
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();
}
options
- blob read optionsStorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) public com.google.cloud.WriteChannel writer(Storage.BlobWriteOption... options)
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();
options
- target blob optionsStorageException
- upon failure@TransportCompatibility(value=HTTP) public URL signUrl(long duration, TimeUnit unit, Storage.SignUrlOption... options)
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:
Storage.SignUrlOption.signWith(ServiceAccountSigner)
StorageOptions
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")));
duration
- time until the signed URL expires, expressed in unit
. The finer
granularity supported is 1 second, finer granularities will be truncatedunit
- time unit of the duration
parameteroptions
- optional URL signing optionsIllegalStateException
- 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@TransportCompatibility(value={HTTP,GRPC}) public Acl getAcl(Acl.Entity entity)
null
if not found.
Example of getting the ACL entry for an entity.
Acl acl = blob.getAcl(User.ofAllAuthenticatedUsers());
StorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) public boolean deleteAcl(Acl.Entity entity)
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
}
true
if the ACL was deleted, false
if it was not foundStorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) public Acl createAcl(Acl acl)
Example of creating a new ACL entry.
Acl acl = blob.createAcl(Acl.of(User.ofAllAuthenticatedUsers(), Acl.Role.READER));
StorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) public Acl updateAcl(Acl acl)
Example of updating a new ACL entry.
Acl acl = blob.updateAcl(Acl.of(User.ofAllAuthenticatedUsers(), Acl.Role.OWNER));
StorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) public List<Acl> listAcls()
Example of listing the ACL entries.
List<Acl> acls = blob.listAcls();
for (Acl acl : acls) {
// do something with ACL entry
}
StorageException
- upon failurepublic Storage getStorage()
Storage
object used to issue requests.public Blob.Builder toBuilder()
BlobInfo
public final boolean equals(Object obj)
Blob.toPb()
metadata representation and Blob.options
instance of StorageOptions are both equal.Copyright © 2023 Google LLC. All rights reserved.