Delete and restore a blob with Java

This article shows how to delete blobs with the Azure Storage client library for Java, and how to restore soft-deleted blobs during the retention period.

Prerequisites

Set up your environment

If you don't have an existing project, this section shows you how to set up a project to work with the Azure Blob Storage client library for Java. For more information, see Get started with Azure Blob Storage and Java.

To work with the code examples in this article, follow these steps to set up your project.

Note

This article uses the Maven build tool to build and run the example code. Other build tools, such as Gradle, also work with the Azure SDK for Java.

Install packages

Open the pom.xml file in your text editor. Install the packages by including the BOM file, or including a direct dependency.

Add import statements

Add the following import statements:

import com.azure.core.http.rest.*;
import com.azure.core.util.*;
import com.azure.storage.blob.*;
import com.azure.storage.blob.models.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

Authorization

The authorization mechanism must have the necessary permissions to delete a blob, or to restore a soft-deleted blob. For authorization with Microsoft Entra ID (recommended), you need Azure RBAC built-in role Storage Blob Data Contributor or higher. To learn more, see the authorization guidance for Delete Blob (REST API) and Undelete Blob (REST API).

Create a client object

To connect an app to Blob Storage, create an instance of BlobServiceClient.

The following example uses BlobServiceClientBuilder to build a BlobServiceClient object using DefaultAzureCredential, and shows how to create container and blob clients, if needed:

// Azure SDK client builders accept the credential as a parameter
// TODO: Replace <storage-account-name> with your actual storage account name
BlobServiceClient blobServiceClient = new BlobServiceClientBuilder()
        .endpoint("https://<storage-account-name>.blob.core.windows.net/")
        .credential(new DefaultAzureCredentialBuilder().build())
        .buildClient();

// If needed, you can create a BlobContainerClient object from the BlobServiceClient
BlobContainerClient containerClient = blobServiceClient
        .getBlobContainerClient("<container-name>");

// If needed, you can create a BlobClient object from the BlobContainerClient
BlobClient blobClient = containerClient
        .getBlobClient("<blob-name>");

To learn more about creating and managing client objects, see Create and manage client objects that interact with data resources.

Delete a blob

Note

When blob soft delete is enabled for a storage account, you can't perform a permanent deletion using client library methods. Using the methods in this article, a soft-deleted blob, blob version, or snapshot remains available until the retention period expires, at which time it's permanently deleted. To learn more about the underlying REST API operation, see Delete Blob (REST API).

To delete a blob, call either of the following 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.

Code samples

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:

Client library resources

See also

  • This article is part of the Blob Storage developer guide for Java. To learn more, see the full list of developer guide articles at Build your Java app.