简体   繁体   中英

How to compute Azure Storage Container Size in 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();
}

In order to get the container size of Azure blob in Java, you would need to iterate through the list of blobs present in it.

val container: CloudBlobContainer = blobClient.getContainerReference(containerName)
val blob: CloudBlockBlob = container.getBlockBlobReference(blobPath)
blob.downloadAttributes()
blob.getProperties.getLength

Make sure you definitely call downloadAttributes else the properties will be empty.

You can refer to this documentation for more details https://docs.microsoft.com/en-us/java/api/com.microsoft.azure.storage.blob.cloudblockblob?view=azure-java-legacy

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM