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

btxsgosb  于 2023-06-24  发布在  Java
关注(0)|答案(2)|浏览(199)

如何删除Azure Blob存储中的文件夹。当我尝试删除文件夹时,我看到以下错误:
com.azure.storage.blob.models.BlobStorageException:状态代码409,“DirectoryIsNotEmpty不允许在非空目录上执行此操作。请求ID:195 b3 f66 - 601 e-0071- 2 edb-094790000000时间:2022-01- 15 T06:47:55.8443865Z”
在sun.reflect.NativeConstructorAccessorImpl.newInstance0(本机方法)在sun.reflect. NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)在sun.reflect. DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)在java.lang.reflect.Constructor.newInstance(Constructor.java:423)在com. azure.core.http.rest.RestProxy.instantiateUnexpectedException(RestProxy.java:389)在com.azure.core.http.rest.RestProxy.lambda$ensureExpectedStatus$7(RestProxy.java:444)

nc1teljy

nc1teljy1#

不确定下面的版本是否是最优化的版本。但它似乎工作:

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();
}
pcrecxhr

pcrecxhr2#

你只需要设置前缀并删除所有的子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());
}

相关问题