使用Java删除Azure Blob存储中的文件夹



如何删除azure blob存储中的文件夹。当我尝试删除文件夹时,我看到以下错误:

com.azure.storage.blob.models.BlobStorageException:状态代码409,"DirectoryIsNotEmptyThis不允许在非空目录上执行操作。请求ID:195b3f66-601e-0071-2edb-094790000000时间:2022-01-15T06:47:55.8443865Z";

在sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native方法(sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessor Impl.java:62(在sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessor Impl.java:45(位于java.lang.reflect.Constructure.newInstance(Constructor.java:423(在com.azure.core.http.RestProxy.instantiateUnexpectedException(RestProxy.java:389(在com.azure.core.http.RestProxy.lambda$ensureExpectedStatus$7(RestProxy.java:444(

不确定以下版本是否是优化程度最高的版本。但它似乎奏效了:

public static void deleteAtLocation(BlobContainerClient container, String historical) {
if (checkIfPathExists(container, historical)) {
List<BlobItem> collect = container.listBlobsByHierarchy(historical).stream().collect(Collectors.toList());
for (BlobItem blobItem : collect) {
String name = blobItem.getName();
if (name.endsWith("/")) {
deleteAtLocation(container, name);
} else container.getBlobClient(name).delete();
}
container.getBlobClient(historical.substring(0, historical.length() - 1)).delete();
}
}
public static boolean checkIfPathExists(BlobContainerClient container, String filePath) {
BlobClient blobClient = container.getBlobClient(filePath);
return blobClient.exists();
}

您只需设置前缀并删除所有子Blob,如果文件夹中没有实际Blob,则默认情况下会删除该文件夹。

public void deleteBlobs(BlobContainerClient blobContainerClient, String path){
log.info("Deleting all blobs at {} in container {}", path, blobContainerClient.getBlobContainerName());
ListBlobsOptions options = new ListBlobsOptions().setPrefix(path)
.setDetails(new BlobListDetails().setRetrieveDeletedBlobs(false).setRetrieveSnapshots(false));
blobContainerClient.listBlobs(options, null).iterator()
.forEachRemaining(item -> blobContainerClient.getBlobClient(item.getName()).delete());
}

最新更新