How to delete a folder in azure blob storage. When I attempt to delete a folder, I see the below error:
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$7(RestProxy.java:444)
CodePudding user response:
Not sure if the below version is the most optimized one. But it appears to work:
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();
}
