This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Note
Access to this page requires authorization. You can trysigning in orchanging directories.
Access to this page requires authorization. You can trychanging directories.
Note
TheBuild from scratch option walks you step by step through the process of creating a new project, installing packages, writing the code, and running a basic console app. This approach is recommended if you want to understand all the details involved in creating an app that connects to Azure Blob Storage. If you prefer to automate deployment tasks and start with a completed project, chooseStart with a template.
Note
TheStart with a template option uses the Azure Developer CLI to automate deployment tasks and starts you off with a completed project. This approach is recommended if you want to explore the code as quickly as possible without going through the setup tasks. If you prefer step by step instructions to build the app, chooseBuild from scratch.
Get started with the Azure Blob Storage client library for Java to manage blobs and containers.
In this article, you follow steps to install the package and try out example code for basic tasks.
In this article, you use theAzure Developer CLI to deploy Azure resources and run a completed console app with just a few commands.
Tip
If you're working with Azure Storage resources in a Spring application, we recommend that you considerSpring Cloud Azure as an alternative. Spring Cloud Azure is an open-source project that provides seamless Spring integration with Azure services. To learn more about Spring Cloud Azure, and to see an example using Blob Storage, seeUpload a file to an Azure Storage Blob.
API reference documentation |Library source code |Package (Maven) |Samples
This section walks you through preparing a project to work with the Azure Blob Storage client library for Java.
Create a Java application namedblob-quickstart.
In a console window (such as PowerShell or Bash), use Maven to create a new console app with the nameblob-quickstart. Type the followingmvn command to create a "Hello world!" Java project.
mvn archetype:generate ` --define interactiveMode=n ` --define groupId=com.blobs.quickstart ` --define artifactId=blob-quickstart ` --define archetypeArtifactId=maven-archetype-quickstart ` --define archetypeVersion=1.4The output from generating the project should look something like this:
[INFO] Scanning for projects...[INFO][INFO] ------------------< org.apache.maven:standalone-pom >-------------------[INFO] Building Maven Stub Project (No POM) 1[INFO] --------------------------------[ pom ]---------------------------------[INFO][INFO] >>> maven-archetype-plugin:3.1.2:generate (default-cli) > generate-sources @ standalone-pom >>>[INFO][INFO] <<< maven-archetype-plugin:3.1.2:generate (default-cli) < generate-sources @ standalone-pom <<<[INFO][INFO][INFO] --- maven-archetype-plugin:3.1.2:generate (default-cli) @ standalone-pom ---[INFO] Generating project in Batch mode[INFO] ----------------------------------------------------------------------------[INFO] Using following parameters for creating project from Archetype: maven-archetype-quickstart:1.4[INFO] ----------------------------------------------------------------------------[INFO] Parameter: groupId, Value: com.blobs.quickstart[INFO] Parameter: artifactId, Value: blob-quickstart[INFO] Parameter: version, Value: 1.0-SNAPSHOT[INFO] Parameter: package, Value: com.blobs.quickstart[INFO] Parameter: packageInPathFormat, Value: com/blobs/quickstart[INFO] Parameter: version, Value: 1.0-SNAPSHOT[INFO] Parameter: package, Value: com.blobs.quickstart[INFO] Parameter: groupId, Value: com.blobs.quickstart[INFO] Parameter: artifactId, Value: blob-quickstart[INFO] Project created from Archetype in dir: C:\QuickStarts\blob-quickstart[INFO] ------------------------------------------------------------------------[INFO] BUILD SUCCESS[INFO] ------------------------------------------------------------------------[INFO] Total time: 7.056 s[INFO] Finished at: 2019-10-23T11:09:21-07:00[INFO] ------------------------------------------------------------------------ ```Switch to the newly createdblob-quickstart folder.
cd blob-quickstartIn side theblob-quickstart directory, create another directory calleddata. This folder is where the blob data files will be created and stored.
mkdir dataOpen thepom.xml file in your text editor.
Addazure-sdk-bom to take a dependency on the latest version of the library. In the following snippet, replace the{bom_version_to_target} placeholder with the version number. Usingazure-sdk-bom keeps you from having to specify the version of each individual dependency. To learn more about the BOM, see theAzure SDK BOM README.
<dependencyManagement> <dependencies> <dependency> <groupId>com.azure</groupId> <artifactId>azure-sdk-bom</artifactId> <version>{bom_version_to_target}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies></dependencyManagement>Then add the following dependency elements to the group of dependencies. Theazure-identity dependency is needed for passwordless connections to Azure services.
<dependency> <groupId>com.azure</groupId> <artifactId>azure-storage-blob</artifactId></dependency><dependency> <groupId>com.azure</groupId> <artifactId>azure-identity</artifactId></dependency>From the project directory, follow steps to create the basic structure of the app:
App.java file in your editorSystem.out.println("Hello world!");import directivesThe code should resemble this framework:
package com.blobs.quickstart;/** * Azure Blob Storage quickstart */import com.azure.identity.*;import com.azure.storage.blob.*;import com.azure.storage.blob.models.*;import java.io.*;public class App{ public static void main(String[] args) throws IOException { // Quickstart code goes here }}WithAzure Developer CLI installed, you can create a storage account and run the sample code with just a few commands. You can run the project in your local development environment, or in aDevContainer.
From an empty directory, follow these steps to initialize theazd template, provision Azure resources, and get started with the code:
Clone the quickstart repository assets from GitHub and initialize the template locally:
azd init --template blob-storage-quickstart-javaYou'll be prompted for the following information:
Log in to Azure:
azd auth loginProvision and deploy the resources to Azure:
azd upYou'll be prompted for the following information:
The deployment might take a few minutes to complete. The output from theazd up command includes the name of the newly created storage account, which you'll need later to run the code.
At this point, the resources are deployed to Azure and the code is almost ready to run. Follow these steps to update the name of the storage account in the code, and run the sample console app:
<storage-account-name> placeholder and replace it with the actual name of the storage account created by theazd up command.pom.xml file. Compile the project by using the followingmvn command:mvn compilemvn packagemvn command to execute the app:mvn exec:javaTo learn more about how the sample code works, seeCode examples.
When you're finished testing the code, see theClean up resources section to delete the resources created by theazd up command.
Azure Blob Storage is optimized for storing massive amounts of unstructured data. Unstructured data doesn't adhere to a particular data model or definition, such as text or binary data. Blob storage offers three types of resources:
The following diagram shows the relationship between these resources.

Use the following Java classes to interact with these resources:
BlobServiceClient class allows you to manipulate Azure Storage resources and blob containers. The storage account provides the top-level namespace for the Blob service.BlobServiceClientBuilder class provides a fluent builder API to help aid the configuration and instantiation ofBlobServiceClient objects.BlobContainerClient class allows you to manipulate Azure Storage containers and their blobs.BlobClient class allows you to manipulate Azure Storage blobs.BlobItem class represents individual blobs returned from a call tolistBlobs.These example code snippets show you how to perform the following actions with the Azure Blob Storage client library for Java:
Important
Make sure you have the correct dependencies in pom.xml and the necessary directives for the code samples to work, as described in thesetting up section.
Note
The Azure Developer CLI template includes a file with sample code already in place. The following examples provide detail for each part of the sample code. The template implements the recommended passwordless authentication method, as described in theAuthenticate to Azure section. The connection string method is shown as an alternative, but isn't used in the template and isn't recommended for production code.
Application requests to Azure Blob Storage must be authorized. Using theDefaultAzureCredential class provided by the Azure Identity client library is the recommended approach for implementing passwordless connections to Azure services in your code, including Blob Storage.
You can also authorize requests to Azure Blob Storage by using the account access key. However, this approach should be used with caution. Developers must be diligent to never expose the access key in an unsecure location. Anyone who has the access key is able to authorize requests against the storage account, and effectively has access to all the data.DefaultAzureCredential offers improved management and security benefits over the account key to allow passwordless authentication. Both options are demonstrated in the following example.
DefaultAzureCredential is a class provided by the Azure Identity client library for Java.DefaultAzureCredential supports multiple authentication methods and determines which method should be used at runtime. This approach enables your app to use different authentication methods in different environments (local vs. production) without implementing environment-specific code.
The order and locations in whichDefaultAzureCredential looks for credentials can be found in theAzure Identity library overview.
For example, your app can authenticate using your Visual Studio Code sign-in credentials with when developing locally. Your app can then use amanaged identity once it has been deployed to Azure. No code changes are required for this transition.
When developing locally, make sure that the user account that is accessing blob data has the correct permissions. You'll needStorage Blob Data Contributor to read and write blob data. To assign yourself this role, you'll need to be assigned theUser Access Administrator role, or another role that includes theMicrosoft.Authorization/roleAssignments/write action. You can assign Azure RBAC roles to a user using the Azure portal, Azure CLI, or Azure PowerShell. For more information about theStorage Blob Data Contributor role, seeStorage Blob Data Contributor. For more information about the available scopes for role assignments, seeUnderstand scope for Azure RBAC.
In this scenario, you'll assign permissions to your user account, scoped to the storage account, to follow thePrinciple of Least Privilege. This practice gives users only the minimum permissions needed and creates more secure production environments.
The following example will assign theStorage Blob Data Contributor role to your user account, which provides both read and write access to blob data in your storage account.
Important
In most cases it will take a minute or two for the role assignment to propagate in Azure, but in rare cases it may take up to eight minutes. If you receive authentication errors when you first run your code, wait a few moments and try again.
In the Azure portal, locate your storage account using the main search bar or left navigation.
On the storage account overview page, selectAccess control (IAM) from the left-hand menu.
On theAccess control (IAM) page, select theRole assignments tab.
Select+ Add from the top menu and thenAdd role assignment from the resulting drop-down menu.
Use the search box to filter the results to the desired role. For this example, search forStorage Blob Data Contributor and select the matching result and then chooseNext.
UnderAssign access to, selectUser, group, or service principal, and then choose+ Select members.
In the dialog, search for your Microsoft Entra username (usually youruser@domain email address) and then chooseSelect at the bottom of the dialog.
SelectReview + assign to go to the final page, and thenReview + assign again to complete the process.
You can authorize access to data in your storage account using the following steps:
Make sure you're authenticated with the same Microsoft Entra account you assigned the role to on your storage account. You can authenticate via the Azure CLI, Visual Studio Code, or Azure PowerShell.
Sign-in to Azure through the Azure CLI using the following command:
az loginTo useDefaultAzureCredential, make sure that theazure-identity dependency is added inpom.xml:
<dependency> <groupId>com.azure</groupId> <artifactId>azure-identity</artifactId></dependency>Add this code to theMain method. When the code runs on your local workstation, it will use the developer credentials of the prioritized tool you're logged into to authenticate to Azure, such as the Azure CLI or Visual Studio Code.
/* * The default credential first checks environment variables for configuration * If environment configuration is incomplete, it will try managed identity */DefaultAzureCredential defaultCredential = new DefaultAzureCredentialBuilder().build();// Azure SDK client builders accept the credential as a parameter// TODO: Replace <storage-account-name> with your actual storage account nameBlobServiceClient blobServiceClient = new BlobServiceClientBuilder() .endpoint("https://<storage-account-name>.blob.core.windows.net/") .credential(defaultCredential) .buildClient();Make sure to update the storage account name in the URI of yourBlobServiceClient. The storage account name can be found on the overview page of the Azure portal.

Note
When deployed to Azure, this same code can be used to authorize requests to Azure Storage from an application running in Azure. However, you'll need to enable managed identity on your app in Azure. Then configure your storage account to allow that managed identity to connect. For detailed instructions on configuring this connection between Azure services, see theAuth from Azure-hosted apps tutorial.
Create a new container in your storage account by calling thecreateBlobContainer method on theblobServiceClient object. In this example, the code appends a GUID value to the container name to ensure that it's unique.
Add this code to the end of theMain method:
// Create a unique name for the containerString containerName = "quickstartblobs" + java.util.UUID.randomUUID();// Create the container and return a container client objectBlobContainerClient blobContainerClient = blobServiceClient.createBlobContainer(containerName);To learn more about creating a container, and to explore more code samples, seeCreate a blob container with Java.
Important
Container names must be lowercase. For more information about naming containers and blobs, seeNaming and Referencing Containers, Blobs, and Metadata.
Upload a blob to a container by calling theuploadFromFile method. The example code creates a text file in the localdata directory to upload to the container.
Add this code to the end of theMain method:
// Create the ./data/ directory and a file for uploading and downloadingString localPath = "./data/";new File(localPath).mkdirs();String fileName = "quickstart" + java.util.UUID.randomUUID() + ".txt";// Get a reference to a blobBlobClient blobClient = blobContainerClient.getBlobClient(fileName);// Write text to the fileFileWriter writer = null;try{ writer = new FileWriter(localPath + fileName, true); writer.write("Hello, World!"); writer.close();}catch (IOException ex){ System.out.println(ex.getMessage());}System.out.println("\nUploading to Blob storage as blob:\n\t" + blobClient.getBlobUrl());// Upload the blobblobClient.uploadFromFile(localPath + fileName);To learn more about uploading blobs, and to explore more code samples, seeUpload a blob with Java.
List the blobs in the container by calling thelistBlobs method. In this case, only one blob has been added to the container, so the listing operation returns just that one blob.
Add this code to the end of theMain method:
System.out.println("\nListing blobs...");// List the blob(s) in the container.for (BlobItem blobItem : blobContainerClient.listBlobs()) { System.out.println("\t" + blobItem.getName());}To learn more about listing blobs, and to explore more code samples, seeList blobs with Java.
Download the previously created blob by calling thedownloadToFile method. The example code adds a suffix of "DOWNLOAD" to the file name so that you can see both files in local file system.
Add this code to the end of theMain method:
// Download the blob to a local file// Append the string "DOWNLOAD" before the .txt extension for comparison purposesString downloadFileName = fileName.replace(".txt", "DOWNLOAD.txt");System.out.println("\nDownloading blob to\n\t " + localPath + downloadFileName);blobClient.downloadToFile(localPath + downloadFileName);To learn more about downloading blobs, and to explore more code samples, seeDownload a blob with Java.
The following code cleans up the resources the app created by removing the entire container using thedelete method. It also deletes the local files created by the app.
The app pauses for user input by callingSystem.console().readLine() before it deletes the blob, container, and local files. This is a good chance to verify that the resources were created correctly, before they're deleted.
Add this code to the end of theMain method:
File downloadedFile = new File(localPath + downloadFileName);File localFile = new File(localPath + fileName);// Clean up resourcesSystem.out.println("\nPress the Enter key to begin clean up");System.console().readLine();System.out.println("Deleting blob container...");blobContainerClient.delete();System.out.println("Deleting the local source and downloaded files...");localFile.delete();downloadedFile.delete();System.out.println("Done");To learn more about deleting a container, and to explore more code samples, seeDelete and restore a blob container with Java.
This app creates a test file in your local folder and uploads it to Blob storage. The example then lists the blobs in the container and downloads the file with a new name so that you can compare the old and new files.
Follow steps to compile, package, and run the code
pom.xml file and compile the project by using the followingmvn command:mvn compilemvn packagemvn command to execute the app:mvn exec:java -D exec.mainClass=com.blobs.quickstart.App -D exec.cleanupDaemonThreads=falseTo simplify the run step, you can addexec-maven-plugin topom.xml and configure as shown below:<plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>1.4.0</version> <configuration> <mainClass>com.blobs.quickstart.App</mainClass> <cleanupDaemonThreads>false</cleanupDaemonThreads> </configuration></plugin>With this configuration, you can execute the app with the following command:mvn exec:javaThe output of the app is similar to the following example (UUID values omitted for readability):
Azure Blob Storage - Java quickstart sampleUploading to Blob storage as blob: https://mystorageacct.blob.core.windows.net/quickstartblobsUUID/quickstartUUID.txtListing blobs... quickstartUUID.txtDownloading blob to ./data/quickstartUUIDDOWNLOAD.txtPress the Enter key to begin clean upDeleting blob container...Deleting the local source and downloaded files...DoneBefore you begin the cleanup process, check yourdata folder for the two files. You can compare them and observe that they're identical.
After you've verified the files and finished testing, press theEnter key to delete the test files along with the container you created in the storage account. You can also useAzure CLI to delete resources.
When you're done with the quickstart, you can clean up the resources you created by running the following command:
azd downYou'll be prompted to confirm the deletion of the resources. Entery to confirm.
Was this page helpful?
Need help with this topic?
Want to try using Ask Learn to clarify or guide you through this topic?
Was this page helpful?
Want to try using Ask Learn to clarify or guide you through this topic?