Package com.google.cloud.storage
Here's a simple usage example the Java Storage client. This example shows how to create a Storage object.
Storage storage = StorageOptions.getDefaultInstance().getService();
BlobId blobId = BlobId.of("bucket", "blob_name");
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build();
Blob blob = storage.create(blobInfo, "Hello, Cloud Storage!".getBytes(UTF_8));
This second example shows how to update an object's content if the object exists.
Storage storage = StorageOptions.getDefaultInstance().getService();
BlobId blobId = BlobId.of("bucket", "blob_name");
Blob blob = storage.get(blobId);
if (blob != null) {
byte[] prevContent = blob.getContent();
System.out.println(new String(prevContent, UTF_8));
WritableByteChannel channel = blob.writer();
channel.write(ByteBuffer.wrap("Updated content".getBytes(UTF_8)));
channel.close();
}
For more detailed code examples, see the sample library.
When using google-cloud from outside of App/Compute Engine, you have to specify a project ID and provide credentials.
Operations in this library are generally thread safe, except for the use of BlobReadChannel and BlobWriteChannel.
The GCS Java client library includes support to GCS via gRPC. When using GCS from Google Compute Engine (GCE) this library enable higher total throughput across large workloads that run on hundreds or thousands of VMs.
At present, GCS gRPC is GA with Allowlist. To access this API, kindly contact the Google Cloud Storage gRPC team at gcs-grpc-contact@google.com with a list of GCS buckets you would like to Allowlist. Please note that while the **service** is GA (with Allowlist), the client library features remain experimental and subject to change without notice. The methods to create, list, query, and delete HMAC keys and notifications are unavailable in gRPC transport.
This example shows how to enable gRPC with Direct Google Access only supported on Google Compute Engine.
StorageOptions options = StorageOptions.grpc().setAttemptDirectPath(true).build();
try (Storage storage = options.getService()) {
BlobId blobId = BlobId.of("bucket", "blob_name");
Blob blob = storage.get(blobId);
if (blob != null) {
byte[] prevContent = blob.getContent();
System.out.println(new String(prevContent, UTF_8));
WritableByteChannel channel = blob.writer();
channel.write(ByteBuffer.wrap("Updated content".getBytes(UTF_8)));
channel.close();
}
}
This example shows how to enable gRPC.
StorageOptions options = StorageOptions.grpc().build();
try (Storage storage = options.getService()) {
BlobId blobId = BlobId.of("bucket", "blob_name");
Blob blob = storage.get(blobId);
if (blob != null) {
byte[] prevContent = blob.getContent();
System.out.println(new String(prevContent, UTF_8));
WritableByteChannel channel = blob.writer();
channel.write(ByteBuffer.wrap("Updated content".getBytes(UTF_8)));
channel.close();
}
}
- See Also:
-
ClassDescriptionAccess Control List for buckets or blobs.Builder for
Aclobjects.Class for ACL Domain entities.Base class for Access Control List entities.Class for ACL Group entities.Class for ACL Project entities.Class for ACL User entities.Root exception for async tasks which fail due to a session being closed.This exception is used to preserve the caller's stacktrace when invoking an async task in a sync context.Perform a resumable upload, uploading at mostbufferSizebytes each flush.An object in Google Cloud Storage.Class for specifying blob source options whenBlobmethods are used.Builder forBlob.Interface representing those methods which can be used to write to and interact with an appendable upload.TheWritableByteChannelreturned fromBlobAppendableUpload.open().Configuration parameters for an appendable uploads channel.Enum providing the possible actions which can be taken during theBlobAppendableUpload.AppendableUploadWriteableByteChannel.close()call.Google Storage Object identifier.Information about an object in Google Cloud Storage.Builder forBlobInfo.Objects of this class hold information on the customer-supplied encryption key, if the blob is encrypted using such a key.This class is meant for internal use only.Represents the payload of a user-defined object context.Defines a blob's Retention policy.A session for reading bytes from a BlobA session to write an object to Google Cloud Storage.A sealed internal implementation only class which provides the means of configuring aBlobWriteSession.Factory class to select and constructBlobWriteSessionConfigs.A Google cloud storage bucket.Class for specifying blob target options whenBucketmethods are used.Class for specifying blob write options whenBucketmethods are used.Class for specifying bucket source options whenBucketmethods are used.Builder forBucket.Google Storage bucket metadata;Deprecated.Configuration for the Autoclass settings of a bucket.Builder forBucketInfo.Deprecated.Use aLifecycleRulewith an actionDeleteLifecycleActionand a conditionLifecycleCondition.Builder.setCreatedBeforeinstead.Customer Managed Encryption (CMEK) enforcement config of a bucket.Customer Supplied Encryption (CSEK) enforcement config of a bucket.The bucket's custom placement configuration for Custom Dual Regions.Deprecated.Use aLifecycleRulewith aDeleteLifecycleActionand aLifecycleConditionwhich is equivalent to a subclass of DeleteRule instead.Google Managed Encryption (GMEK) enforcement config of a bucket.The bucket's hierarchical namespace (Folders) configuration.The Bucket's IAM Configuration.Builder forIamConfigurationA buckets IP filtering configuration.The public network IP address ranges that can access the bucket and its data.The list of VPC networks that can access the bucket.Deprecated.Use aLifecycleRulewith aDeleteLifecycleActionand a conditionLifecycleCondition.Builder.setIsLiveinstead.Lifecycle rule for a bucket.Base class for the Action to take when a Lifecycle Condition is met.Condition for a Lifecycle rule, specifies under what criteria an Action should be executed.Builder forLifecycleCondition.The bucket's logging configuration, which defines the destination bucket and optional name prefix for the current bucket's logs.Deprecated.Use aLifecycleRulewith aDeleteLifecycleActionand a conditionLifecycleCondition.Builder.setNumberOfNewerVersionsinstead.Public Access Prevention enum with expected values.The bucket's soft delete policy.There are scenarios in which disk space is more plentiful than memory space.Canonical extension header serializer.Google Storage blob copy writer.Cross-Origin Resource Sharing (CORS) configuration for a bucket.CORS configuration builder.Class for a CORS origin.Default Configuration to represent uploading to Google Cloud Storage in a chunked manner.Base class used for flush policies which are responsible for configuring an upload channel's behavior with regard to flushes.Define aFlushPolicywhere a max number of bytes will be flushed to GCS per flush.Define aFlushPolicywhere a min number of bytes will be required before a flush GCS happens.Internal implementation detail, only public to allow forSerializablecompatibility inServiceOptions.Deprecated.HMAC key for a service account.Builder forHmacKeyobjectsThe metadata for a service account HMAC key.Builder forHmacKeyMetadataobjectsHttp method supported by Storage service.Internal implementation detail, only public to allow forSerializable.Internal implementation detail, only public to allow forSerializable.There are scenarios in which disk space is more plentiful than memory space.Produce a newRangeSpecrelative to the providedoffsetandprev, where the RangeSpec will have a maxLength set to the lesser ofprev.maxLengthandthis.maxLength.A client for interacting with Google Cloud Storage's Multipart Upload API.Settings for configuring theMultipartUploadClient.The class representing Pub/Sub notifications for the Storage.Builder forNotification.The class representing Pub/Sub Notification metadata for the Storage.Builder forNotificationInfo.Builder forNotificationInfo.Option<O extends com.google.cloud.storage.UnifiedOpts.Opt>Deprecated.Immutable config builder to configure BlobWriteSession instances to perform Parallel Composite Uploads.A strategy which dictates how buffers are to be used for individual parts.Class which will be used to supply an Executor where work will be submitted when performing a parallel composite upload.A cleanup strategy which will dictate what cleanup operations are performed automatically when performing a parallel composite upload.A Decorator which is used to manipulate metadata fields, specifically on the part objects created in a Parallel Composite UploadA naming strategy which will be used to generate a name for a part or intermediary compose object.An exception which provides access to created objects during a Parallel Composite Upload that did not finish successfully.Presigned V4 post policy.Class for a specific POST policy document condition.A helper class for specifying conditions in a V4 POST Policy document.A helper class to define fields to be specified in a V4 POST request.Class for a V4 POST Policy document.Defines a range with a begin offset and optional maximum length.A specialized BiFunction to produce aRangeSpecgiven an offset and a possible previousRangeSpec.Read a range ofbytes as a non-blockingScatteringByteChannelRead a range ofbytes as anApiFuture<byte[]>Read from the object as aSeekableByteChannelReadProjectionConfig<Projection>Base class to represent a config for reading from aBlobReadSession.Factory class to selectReadProjectionConfigs.The data of a singleUploadPartin a GCS XML MPU.Enums for the Recovery Point Objective (RPO) of dual-region buckets, which determines how fast data is replicated between regions.A service account, with its specified scopes, authorized for this instance.Signature Info holds payload components of the string that requires signing.An interface for Google Cloud Storage.Class for specifying blob get options.Class for specifying blob list options.Class for specifying blob restore options *Class for specifying blob source options.Class for specifying blob target options.Class for specifying blob write options.Class for specifying bucket get options.Class for specifying bucket list options.Class for specifying bucket source options.Class for specifying bucket target options.A class to contain all information needed for a Google Cloud Storage Compose operation.Class for Compose source blobs.A class to contain all information needed for a Google Cloud Storage Copy operation.Class for specifying createHmacKey optionsClass for specifying deleteHmacKey optionsClass for specifying getHmacKey optionsClass for specifying listHmacKeys optionsA class to contain all information needed for a Google Cloud Storage Object Move.Class for specifying Post Policy V4 optionsClass for specifying signed URL options.Class for specifying updateHmacKey optionsA batch of operations to be submitted to Google Cloud Storage using a single RPC request.This class holds a single result of a batch call to Cloud Storage.Set of utility methods for working with non-blocking channels returned by this library.Enums for the storage classes.Storage service exception.An interface for Storage factories.Deprecated.Deprecated.A factory class which is used to provide access toResultRetryAlgorithmfor idempotent and non-idempotent calls made viaStorage.IAM roles specific to Storage.Annotation which is used to convey which Cloud Storage API a class or method has compatibility with.Enum representing the transportscom.google.cloud.storageclasses have implementations for.Public components which exist to support zero-copy data accessRepresents an object that can be accessed as aByteString, but has a lifecycle that requires being explicitly closed in order to free up resources.
LifecycleRulewith aDeleteLifecycleActionand useLifecycleCondition.Builder.setAgeinstead.