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

Delete a folder in Azure Blob Storage with Java

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

com.azure.storage.blob.models.BlobStorageException: Status code 409, "DirectoryIsNotEmptyThis operation is not permitted on a non-empty directory. RequestId:195b3f66-601e-0071-2edb-094790000000 Time:2022-01-15T06:47:55.8443865Z"

at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:423) at com.azure.core.http.rest.RestProxy.instantiateUnexpectedException(RestProxy.java:389) at com.azure.core.http.rest.RestProxy.lambda$ensureExpectedStatus(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();
}