Редактиране

Споделяне чрез


List blobs with Java

This article shows how to list blobs with the Azure Storage client library for Java.

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.storage.blob.*;
import com.azure.storage.blob.models.*;

Authorization

The authorization mechanism must have the necessary permissions to list a blob. For authorization with Microsoft Entra ID (recommended), you need Azure RBAC built-in role Storage Blob Data Reader or higher. To learn more, see the authorization guidance for List Blobs (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.

About blob listing options

When you list blobs from your code, you can specify options to manage how results are returned from Azure Storage. You can specify the number of results to return in each set of results, and then retrieve the subsequent sets. You can specify a prefix to return blobs whose names begin with that character or string. And you can list blobs in a flat listing structure, or hierarchically. A hierarchical listing returns blobs as though they were organized into folders.

To list the blobs in a storage account, call one of these methods:

Manage how many results are returned

By default, a listing operation returns up to 5000 results at a time, but you can specify the number of results that you want each listing operation to return. The examples presented in this article show you how to return results in pages. To learn more about pagination concepts, see Pagination with the Azure SDK for Java.

Filter results with a prefix

To filter the list of blobs, pass a string as the prefix parameter to ListBlobsOptions.setPrefix(String prefix). The prefix string can include one or more characters. Azure Storage then returns only the blobs whose names start with that prefix.

Flat listing versus hierarchical listing

Blobs in Azure Storage are organized in a flat paradigm, rather than a hierarchical paradigm (like a classic file system). However, you can organize blobs into virtual directories in order to mimic a folder structure. A virtual directory forms part of the name of the blob and is indicated by the delimiter character.

To organize blobs into virtual directories, use a delimiter character in the blob name. The default delimiter character is a forward slash (/), but you can specify any character as the delimiter.

If you name your blobs using a delimiter, then you can choose to list blobs hierarchically. For a hierarchical listing operation, Azure Storage returns any virtual directories and blobs beneath the parent object. You can call the listing operation recursively to traverse the hierarchy, similar to how you would traverse a classic file system programmatically.

Use a flat listing

By default, a listing operation returns blobs in a flat listing. In a flat listing, blobs aren't organized by virtual directory.

The following example lists the blobs in the specified container using a flat listing:

public void listBlobsFlat(BlobContainerClient blobContainerClient) {
    System.out.println("List blobs flat:");

    blobContainerClient.listBlobs()
            .forEach(blob -> System.out.printf("Name: %s%n", blob.getName()));
}

Sample output is similar to:

List blobs flat:
Name: file4.txt
Name: folderA/file1.txt
Name: folderA/file2.txt
Name: folderA/folderB/file3.txt

You can also specify options to filter list results or show additional information. The following example lists blobs with a specified prefix, and also lists deleted blobs:

public void listBlobsFlatWithOptions(BlobContainerClient blobContainerClient) {
    ListBlobsOptions options = new ListBlobsOptions()
            .setMaxResultsPerPage(2) // Low number for demonstration purposes
            .setDetails(new BlobListDetails()
                    .setRetrieveDeletedBlobs(true));

    System.out.println("List blobs flat:");

    int i = 0;
    Iterable<PagedResponse<BlobItem>> blobPages = blobContainerClient.listBlobs(options, null).iterableByPage();
    for (PagedResponse<BlobItem> page : blobPages) {
        System.out.printf("Page %d%n", ++i);
        page.getElements().forEach(blob -> {
            System.out.printf("Name: %s, Is deleted? %b%n",
                    blob.getName(),
                    blob.isDeleted());
        });
    }
}

Sample output is similar to:

List blobs flat:
Page 1
Name: file4.txt, Is deleted? false
Name: file5-deleted.txt, Is deleted? true
Page 2
Name: folderA/file1.txt, Is deleted? false
Name: folderA/file2.txt, Is deleted? false
Page 3
Name: folderA/folderB/file3.txt, Is deleted? false

Note

The sample output shown assumes that you have a storage account with a flat namespace. If you've enabled the hierarchical namespace feature for your storage account, directories are not virtual. Instead, they are concrete, independent objects. As a result, directories appear in the list as zero-length blobs.

For an alternative listing option when working with a hierarchical namespace, see List directory contents (Azure Data Lake Storage).

Use a hierarchical listing

When you call a listing operation hierarchically, Azure Storage returns the virtual directories and blobs at the first level of the hierarchy.

To list blobs hierarchically, use the following method:

The following example lists the blobs in the specified container using a hierarchical listing:

public void listBlobsHierarchicalListing(BlobContainerClient blobContainerClient, String prefix/* ="" */) {
    String delimiter = "/";
    ListBlobsOptions options = new ListBlobsOptions()
            .setPrefix(prefix);

    blobContainerClient.listBlobsByHierarchy(delimiter, options, null)
            .forEach(blob -> {
                if (blob.isPrefix()) {
                    System.out.printf("Virtual directory prefix: %s%n", delimiter + blob.getName());
                    listBlobsHierarchicalListing(blobContainerClient, blob.getName());
                } else {
                    System.out.printf("Blob name: %s%n", blob.getName());
                }
            });
}

Sample output is similar to:

List blobs hierarchical:
Blob name: file4.txt
Virtual directory prefix: /folderA/
Blob name: folderA/file1.txt
Blob name: folderA/file2.txt
Virtual directory prefix: /folderA/folderB/
Blob name: folderA/folderB/file3.txt

Note

Blob snapshots cannot be listed in a hierarchical listing operation.

Resources

To learn more about how to list 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 listing blobs use the following REST API operation:

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.