Delete and restore a blob with Java

This article shows how to delete blobs with the Azure Storage client library for Java. If you've enabled soft delete for blobs, you can restore deleted blobs during the retention period.

Prerequisites

  • This article assumes you already have a project set up to work with the Azure Blob Storage client library for Java. To learn about setting up your project, including package installation, adding import directives, and creating an authorized client object, see Get Started with Azure Storage and Java.
  • The authorization mechanism must have permissions to delete a blob, or to restore a soft-deleted blob. To learn more, see the authorization guidance for the following REST API operations:

Delete a blob

To delete a blob, call one of these methods:

The following example deletes a blob:

public void deleteBlob(BlobClient blobClient) {
    blobClient.delete();
}

If the blob has any associated snapshots, you must delete all of its snapshots to delete the blob. The following example deletes a blob and its snapshots with a response:

public void deleteBlobWithSnapshots(BlobClient blobClient) {
    Response<Boolean> response = blobClient.deleteIfExistsWithResponse(DeleteSnapshotsOptionType.INCLUDE, null,
            null,
            new Context("key", "value"));
    if (response.getStatusCode() == 404) {
        System.out.println("Blob does not exist");
    } else {
        System.out.printf("Delete blob completed with status %d%n", response.getStatusCode());
    }
}

To delete only the snapshots and not the blob itself, you can pass the parameter DeleteSnapshotsOptionType.ONLY.

Restore a deleted blob

Blob soft delete protects an individual blob and its versions, snapshots, and metadata from accidental deletes or overwrites by maintaining the deleted data in the system for a specified period of time. During the retention period, you can restore the blob to its state at deletion. After the retention period has expired, the blob is permanently deleted. For more information about blob soft delete, see Soft delete for blobs.

You can use the Azure Storage client libraries to restore a soft-deleted blob or snapshot.

How you restore a soft-deleted blob depends on whether or not your storage account has blob versioning enabled. For more information on blob versioning, see Blob versioning. See one of the following sections, depending on your scenario:

Restore soft-deleted objects when versioning is disabled

To restore deleted blobs, call the following method:

This method restores the content and metadata of a soft-deleted blob and any associated soft-deleted snapshots. Calling this method for a blob that hasn't been deleted has no effect.

public void restoreBlob(BlobClient blobClient) {
    blobClient.undelete();
}

Restore soft-deleted objects when versioning is enabled

If a storage account is configured to enable blob versioning, deleting a blob causes the current version of the blob to become the previous version. To restore a soft-deleted blob when versioning is enabled, copy a previous version over the base blob. You can use the following method:

This method restores the content and metadata of a soft-deleted blob and any associated soft-deleted snapshots. Calling this method for a blob that hasn't been deleted has no effect.

public void restoreBlobVersion(BlobContainerClient containerClient, BlobClient blobClient){
    // List blobs in this container that match the prefix
    // Include versions in the listing
    ListBlobsOptions options = new ListBlobsOptions()
            .setPrefix(blobClient.getBlobName())
            .setDetails(new BlobListDetails()
                    .setRetrieveVersions(true));
    Iterator<BlobItem> blobItem = containerClient.listBlobs(options, null).iterator();
    List<String> blobVersions = new ArrayList<>();
    while (blobItem.hasNext()) {
        blobVersions.add(blobItem.next().getVersionId());
    }

    // Sort the list of blob versions and get the most recent version ID
    Collections.sort(blobVersions, Collections.reverseOrder());
    String latestVersion = blobVersions.get(0);

    // Get a client object with the name of the deleted blob and the specified version
    BlobClient blob = containerClient.getBlobVersionClient("sampleBlob.txt", latestVersion);

    // Restore the most recent version by copying it to the base blob
    blobClient.copyFromUrl(blob.getBlobUrl());
}

Restore soft-deleted blobs and directories (hierarchical namespace)

Important

This section applies only to accounts that have a hierarchical namespace.

  1. To get started, open the pom.xml file in your text editor. Add the following dependency element to the group of dependencies.

    <dependency>
      <groupId>com.azure</groupId>
      <artifactId>azure-storage-file-datalake</artifactId>
      <version>12.6.0</version>
    </dependency>
    
  2. Then, add these imports statements to your code file.

    Put imports here
    
  3. The following snippet restores a soft-deleted file named my-file.

    This method assumes that you've created a DataLakeServiceClient instance. To learn how to create a DataLakeServiceClient instance, see Connect to the account.

    
    public void RestoreFile(DataLakeServiceClient serviceClient){
    
        DataLakeFileSystemClient fileSystemClient =
            serviceClient.getFileSystemClient("my-container");
    
        DataLakeFileClient fileClient =
            fileSystemClient.getFileClient("my-file");
    
        String deletionId = null;
    
        for (PathDeletedItem item : fileSystemClient.listDeletedPaths()) {
    
            if (item.getName().equals(fileClient.getFilePath())) {
               deletionId = item.getDeletionId();
            }
        }
    
        fileSystemClient.restorePath(fileClient.getFilePath(), deletionId);
     }
    
    

    If you rename the directory that contains the soft-deleted items, those items become disconnected from the directory. If you want to restore those items, you'll have to revert the name of the directory back to its original name or create a separate directory that uses the original directory name. Otherwise, you'll receive an error when you attempt to restore those soft-deleted items.

Resources

To learn more about how to delete blobs and restore deleted blobs using the Azure Blob Storage client library for Java, see the following resources.

REST API operations

The Azure SDK for Java contains libraries that build on top of the Azure REST API, allowing you to interact with REST API operations through familiar Java paradigms. The client library methods for deleting blobs and restoring deleted blobs use the following REST API operations:

Code samples

Client library resources

See also