Very late to the party, but here for current Google searches. We can efficiently delete multiple blobs using com.google.cloud.storage.StorageBatch .
Like this:
public static void rmdir(Storage storage, String bucket, String dir) { StorageBatch batch = storage.batch(); Page<Blob> blobs = storage.list(bucket, Storage.BlobListOption.currentDirectory(), Storage.BlobListOption.prefix(dir)); for(Blob blob : blobs.iterateAll()) { batch.delete(blob.getBlobId()); } batch.submit(); }
This should work MUCH faster than deleting one at a time when your cart / folder contains a non-trivial number of items.
Edit, as this gets a little attention, I will demonstrate error handling:
public static boolean rmdir(Storage storage, String bucket, String dir) { List<StorageBatchResult<Boolean>> results = new ArrayList<>(); StorageBatch batch = storage.batch(); try { Page<Blob> blobs = storage.list(bucket, Storage.BlobListOption.currentDirectory(), Storage.BlobListOption.prefix(dir)); for(Blob blob : blobs.iterateAll()) { results.add(batch.delete(blob.getBlobId())); } } finally { batch.submit(); } return results.stream().allMatch(r -> r != null && r.get()); }
This method will: Delete every blob in the given folder of this segment, returning true if so. Otherwise, the method will return false. You can refer to the batch.delete() return method for better understanding and protection against errors.
To make sure ALL items are deleted, you can name it as follows:
boolean success = false while(!success)) { success = rmdir(storage, bucket, dir); }
Meettitan
source share