如何在 Java 中计算 Azure 存储容器大小?

2022-01-24 00:00:00 azure azure-blob-storage containers java

While the following link details the way you can compute the storage size using C#, I don't see similar methods in Java. Appreciate if someone can post a sample code for Java please. Azure Storage container size

解决方案

Here is my sample code. For more details, please refer to the javadocs of Azure Storage SDK for Java.

String accountName = "<your-storage-account-name>";
String accountKey = "<your-storage-account-key>";
String storageConnectionString = "DefaultEndpointsProtocol=https;AccountName=%s;AccountKey=%s";
String connectionString = String.format(storageConnectionString, accountName, accountKey);
CloudStorageAccount account = CloudStorageAccount.parse(connectionString);
CloudBlobClient client = account.createCloudBlobClient();
String containerName = "mycontainer";
CloudBlobContainer container = client.getContainerReference(containerName);
long size = 0L;
Iterable<ListBlobItem> blobItems = container.listBlobs();
for (ListBlobItem blobItem : blobItems) {
    if (blobItem instanceof CloudBlob) {
        CloudBlob blob = (CloudBlob) blobItem;
        size += blob.getProperties().getLength();
    }
}

If you need to count size for a container include snapshot, please using the code below to get the blob list.

// If count blob size for a container include snapshots
String prefix = null;
boolean useFlatBlobListing = true;
EnumSet<BlobListingDetails> listingDetails = EnumSet.of(BlobListingDetails.SNAPSHOTS);
BlobRequestOptions options = null;
OperationContext opContext = null;
Iterable<ListBlobItem> blobItems = container.listBlobs(prefix, useFlatBlobListing, listingDetails, options, opContext);

If just count size for snapshots in a container, please using the code below to check a blob whether is a snapshot.

if (blob.isSnapshot()) {
    size += blob.getProperties().getLength();
}

相关文章