‘2124, 5:12 PM (Quickstar: Azure Blob Storage library - Java | Microsoft Lear
Quickstart: Azure Blob Storage client
library for Java
Article + 04/10/2023
Get started with the Azure Blob Storage client library for Java to manage blobs and
containers. Follow these steps to install the package and try out example code for basic
tasks.
Q Tip
If you're working with Azure Storage resources in a Spring application, we recommend
that you consider Spring 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, see
Upload a file to an Azure Storage Blob.
APL reference documentation | Library source code | Package (Maven) _| Samples
Prerequisites
‘© Azure account with an active subscription - create an account for free
Azure Storage account - create a storage account,
Java Development Kit (JDK) version 8 or above.
‘Apache Maven
Setting up
This section walks you through preparing a project to work with the Azure Blob Storage
client library for Java.
Create the project
Create a Java application named blob-quickstart.
nttps:leam microsotcomlen-uslazurelstorage/olobsistorage-quickstat-blbs java7tabs-powershel%2Cmanaged-identiy'2Croles-azure-portais2... 1/18‘2124, 5:12 PM (Quickstar: Azure Blob Storage library - Java | Microsoft Lear
1. In a console window (such as PowerShell or Bash), use Maven to create a new console
app with the name blob-quickstart. Type the following mvn command to create a
“Hello world!" Java project.
PowerShell
PowerShell
mvn archetype: generate
--define
-define
-define
interactiveMod
groupId=com. blobs. quickstart ~
artifact
Lob-quickstart ~
archetypeArtifactId=maven-archetype-quickstart
archetypeVersion=1.4
-define
-define
2. The output from generating the project should look something like this:
Console
[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-plugil
sources @ standalone-pom >>>
[INFO]
[INFO] <<< maven-archetype-plugi
sources @ standalone-pom <<<
[1NFo]
[INFO]
[INFO] --- maven-archetype-plugin:3.1.2:generate (default-cli) @ stand-
alone-pom ---
[INFO] Generating project in Batch mode
[INFO] -
enerate (default-cli) > generate-
enerate (default-cli) < generate-
[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.-SNAPSHOT
ntps:leam microsotcomlen-uslazurelstorage/olobsistorage-quicksta- blobs java7tabs=powershel%s2Cmanaged-identiy'2Croles-azure-portais2... 2/18‘i204, 5:12 Pm
INFO)
(INFO)
[INFO]
[INFO]
[INFO]
{INFO}
(INFO)
start
(INFO)
[INFO]
INFO)
(INFO)
(INFO)
[xNFo]
(Quickstar: Azure Blob Storage library - Java | Microsoft Lear
Parameter: package, Value: com.blobs. quickstart
Parameter: packageInPathFormat, Value: com/blobs/quickstart
Parameter: version, Value: 1.0-SNAPSHOT
Parameter: package, Value: com.blobs.quickstart
Parameter: groupId, Value: com.blobs.quickstart
artifactId, Value: blob-quickstart
Project created from Archetype in dir: C:\QuickStarts\blob-quick-
Parameter
BUILD SUCCESS
Total time: 7.056 s
Finished at: 2019-10-23711:09:21-07:00
3. Switch to the newly created blob-quickstart folder.
Console
cd blob-quickstart
4. In side the blob-quickstart directory, create another directory called data. This folder is
where the blob data files will be created and stored.
Console
mkdir data
Install the packages
Open the pom.xml file in your text editor.
‘Add azure-sdk-bom to take a dependency on the latest version of the library. In the
following snippet, replace the {bon_version_to_target} placeholder with the version
number. Using azure-sdk-bom keeps you from having to specify the version of each
individual dependency. To learn more about the BOM, see the Azure SDK BOM README
XML
nttps:leam microsotcomlen-uslazurelstorago/olobsistorage-quicksta- blobs java7tabs=powershel%s2Cmanaged-identiy%2Croles-azure-portaie2... 3/16‘2124, 5:12 PM (Quickstar: Azure Blob Storage library - Java | Microso Lear
com.azure
azure-sdk-bom
{bom_version_to_target}
‘pom
import
Then add the following dependency elements to the group of dependencies. The azure-
identity dependency is needed for passwordless connections to Azure services.
XML
com.azure
azure-storage-blob
com.azure
azure-identity
Set up the app framework
structure of the app:
From the project directory, follow steps to create the basi
1. Navigate to the /src/main/java/com/blobs/quickstart directory
2. Open the App. java file in your editor
3. Delete the line systen.out.printin("Hello world!");
4, Add the necessary inport directives
The code should resemble this framework:
Java
package con.blobs. quickstart;
ye
* Azure Blob Storage quickstart
7]
ntps:/leam microsotcomlen-uslazurelstorage/olobsistorage-quicksta-blbs java7tabs=powershel%2Cmanaged-identiy'2Croles-azure-portaie2... 4/16‘12224, 512 PM Quickstart: Azure Blob Storage library Java | Microsoft Learn
import com.azure.identity.*;
import com.azure.storage.blob.*;
import com.azure.storage.blob.models.*5
import java.io.*;
public class App
{
public static void main(String[] args) throws IOException
{
// Quickstart code goes here
+
+
Object model
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 storage account
‘* Acontainer in the storage account
© Ablob in the container
The following diagram shows the relationship between these resources.
— pictures 7— ES] img001jpg
Ea img002jpg
MM movies, mova
Use the following Java classes to interact with these resources:
‘* BlobServiceClient: The slobserviceclient class allows you to manipulate Azure
Storage resources and blob containers. The storage account provides the top-level
namespace for the Blob service.
‘* BlobServiceClientBuilder: The BlobServiceClientBuilder class provides a fluent
builder API to help aid the configuration and instantiation of slobserviceClient
objects.
‘* BlobContainerClient: The BlobContainerclient class allows you to manipulate Azure
Storage containers and their blobs
‘* BlobClient: The BlobClient class allows you to manipulate Azure Storage blobs.
/ntps:leam microsof. comier-us/azure/storagetblobs/storage-quickstar-blobs java tabs=powershellk2Cmanagedidentty2Croles-azure-portalk2... S16‘2124, 5:12 PM (Quickstar: Azure Blob Storage library - Java | Microsoft Lear
* Blobltem: The Blobrtem class represents individual blobs returned from a call to
listBlobs.
Code examples
These example code snippets show you how to perform the following actions with the
Azure Blob Storage client library for Java
* Authenticate to Azure and authorize access to blob data
© Create a container
‘* Upload blobs to a container
* List the blobs in a container
* Download blobs
* Delete a container
© Important
Make sure you have the correct dependencies in pom.xml and the necessary directives
for the code samples to work, as described in the setting up section
Authenticate to Azure and authorize access to blob data
Application requests to Azure Blob Storage must be authorized. Using the
Defaultazurecredential 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
Passwordless (Recommended)
nttps:leam microsotcomlen-uslazurelstorage/olobsistorage-quicksta-blbs java7tabs=powershel%s2Cmanaged-identiy'2Croles-azure-portalis2... 6/16‘2124, 5:12 PM (Quickstar: Azure Blob Storage library - Java | Microsoft Lear
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 which DefaultazureCredential looks for credentials can be
found in the Azure 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 a managed identity
‘once it has been deployed to Azure. No code changes are required for this transition,
Assign roles to your Microsoft Entra user account
When developing locally, make sure that the user account that is accessing blob data
has the correct permissions. You'll need Storage Blob Data Contributor to read and
write blob data. To assign yourself this role, you'll need to be assigned the User Access
Administrator role, or another role that includes the
Microsoft. Authorization/roleAssignments/write action. You can assign Azure RBAC
roles to a user using the Azure portal, Azure CLI, or Azure PowerShell. You can learn
more about the available scopes for role assignments on the scope overview page
In this scenario, you'll assign permissions to your user account, scoped to the storage
account, to follow the Principle of Least Privilege. This practice gives users only the
minimum permissions needed and creates more secure production environments
The following example will assign the Storage 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.
ntps:/leam microsotcomlen-uslazurelstorage/olobsistorage-quickstart-blbs java7tabs=powershel%s2Cmanaged-identiy'2Croles-azure-portais2... 7/18‘yozi24, 5:12 PM (Quickstar: Azure Blob Storage library - Java | Microsoft Lear
‘Azure portal
1. In the Azure portal, locate your storage account using the main search bar or
left navigation.
2. On the storage account overview page, select Access control (IAM) from the
left-hand menu.
3. On the Access control (IAM) page, select the Role assignments tab.
4, Select + Add from the top menu and then Add role assignment from the
resulting drop-down menu.
Bg identitymigrationstorage | Access Control (AM)
a
5. Use the search box to filter the results to the desired role. For this example,
search for Storage Blob Data Contributor and select the matching result and
then choose Next.
6. Under Assign access to, select User, group, or service principal, and then
choose + Select members.
7. In the dialog, search for your Microsoft Entra username (usually your
user@domain email address) and then choose Select at the bottom of the
dialog
8, Select Review + assign to go to the final page, and then Review + a
again to complete the process.
/ntps:leam microsof. comier-us/azure/storagetblobs/storage-quickstar-blobs java tabs=powershellk2Cmanagedidentity2Croles-azure-portal’k2... 8/16‘yaaa 5:12 PM (Quickstart Azure Blob Storage library - Java | MirosoM Learn
Sign-in and connect your app code to Azure using
DefaultAzureCredential
You can authorize access to data in your storage account using the following steps:
1, 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
‘Azure CLI
Sign-in to Azure through the Azure CLI using the following command:
Azure CU
az login
2. To use Defaultazurecredential, make sure that the azure-identity dependency is.
added in pom.xml:
XML
com.azure
azure-identity
3. Add this code to the main 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
Java
*
* The default credential first checks environment variables for con-
figuration
* If environment configuration is incomplete, it will try managed
identity
”
DefaultAzureCredential defaultCredential = new
DefaultazureCredentialBuilder().build();
nitps:/leam microsot.comlen-uslazurelstorage/olobsistorage-quickstar-blbs java7tabs-powershel%s2Cmanaged-identiy'2Croles-azure-portais2... 9/16‘12224, 512 PM Quickstart: Azure Blob Storage library - Java | Microsoft Learn
// Bzure SDK client builders accept the credential as a parameter
// TODO: Replace
with your actual storage ac-
count name
BlobServiceClient blobServiceClient = new BlobServiceClientBuilder()
sendpoint (“https: // .blob. core.windows .net/")
- credential (defaultCredential)
-buildClient();
4, Make sure to update the storage account name in the URI of your
BlobServiceClient.. The storage account name can be found on the overview
page of the Azure portal.
«a [dentitymigrationstorage] ° =
F upload 0 © retesh
Essentials
Resource group nave): slenridentity-reamp
6 ox Location east us
Pomanyesondary Location: Pamany Est US Seconda’ Wast US
& diagnose and solve problems
suesenation (cau crete Senge Content Team Tt
a ecese Conte any
subseristion
© cetisesser isk Primary: avaiable, Secondary: avaiable
F events
Tes exit (ck her to ad tags
a storage brouser
© 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 the
Auth from Azure-hosted apps tutorial.
Create a container
/ntps:leam microsof. comier-us/azure/storagetblobs/storage-quickstar-blobs java tabs=powershellk2Cmanagedidentyk2Croles-azure-portal’s.. 10/16‘2124, 5:12 PM (Quickstar: Azure Blob Storage library - Java | Microsoft Lear
Decide on a name for the new container. The code below appends a UUID value to the
container name to ensure that it's unique.
@ Important
Container names must be lowercase. For more information about naming containers
and blobs, see Naming and Referencing Containers, Blobs, and Metadata.
Next, create an instance of the BlobContainerClient class, then call the create method to
actually create the container in your storage account.
‘Add this code to the end of the Main method:
Java
// Create a unique name for the container
String containerName = “quickstartblobs" + java.util.UUID.randomUUID();
// Create the container and return a container client object
BlobContainerClient blobContainerClient =
blobServiceClient.createBlobContainer(containerName) ;
To learn more about creating a container, and to explore more code samples, see Create a
blob container with Java.
Upload blobs to a container
Add this code to the end of the main method:
Java
// Create a local file in the ./data/ directory for uploading and downloading
String localpath = "./data/";
String fileName = “quickstart” + java.util.UUID.randomUUID() + ".txt";
// Get a reference to a blob
BlobClient blobClient = blobContainerClient.getBlobClient (fileName);
// Write text to the file
Fileliriter writer = null;
try
{
writer = new FileWiniter(localPath + fileName, true);
ntps:leam microsotcomlen-uslazurelstorage/olobsistorage-quicksta-blbs java7tabs-powershel%s2Cmanaged-identiy'2Croles-azure-portalis... 11/18‘2124, 5:12 PM (Quickstar: Azure Blob Storage library - Java | Microsoft Lear
writer write("Hello, World!");
writer.close();
3
catch (IOException ex)
{
system.out. print1n(ex.getMessage()) 5
+
‘system.out.print1n("\nUploading to Blob storage as blob:\n\t" +
blobClient.getBlobUr1());
// Upload the blob
blobClient.uploadFronFile(localPath + fileName);
The code snippet completes the following steps:
1. Creates a text file in the local data directory.
2, Gets a reference to a BlobClient object by calling the getBlobClient method on the
container from the Create a container section.
3. Uploads the local text file to the blob by calling the uploadFromfile method. This
method creates the blob if it doesn't already exist, but won't overwrite it if it does.
To learn more about uploading blobs, and to explore more code samples, see Upload a
blob with Java.
List the blobs in a container
List the blobs in the container by calling the list8lobs 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 the main method:
Java
system.out.printIn("\nListing blobs...
// List the blob(s) in the container.
for (BlobIten blobIten : blobContainerClient.1ist8lobs()) {
System.out.println("\t" + blobiten.getName());
}
To learn more about listing blobs, and to explore more code samples, see List blobs with
Java.
nitps:/leam microsotcomlen-us/azurelstorage/olobsistorage-quickstat- blobs java7tabs-powershel%s2Cmanaged-identiy'2Croles-azure-portali.... 12/18‘2124, 5:12 PM (Quickstar: Azure Blob Storage library - Java | Microsoft Lear
Download blobs
Download the previously created blob by calling the downloadToFile 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 the main method
Java
J Download the blob to a local file
// Append the string "DOWNLOAD" before the .txt extension for comparison pur-
poses
String downloadFileName = fileName.replace(".txt", "DOWNLOAD.txt");
‘System.out.printIn("\nDownloading blob to\n\t * + localPath + downloadFile-
Name) ;
blobClient .downloadToFile(localPath + downloadFileNane) ;
To learn more about downloading blobs, and to explore more code samples, see Download
a blob with Java.
Delete a container
The following code cleans up the resources the app created by removing the entire
container using the delete method. It also deletes the local files created by the app.
The app pauses for user input by calling systen.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 the Main method:
Java
File downloadedFile = new File(localPath + downloadFileName) ;
File localFile = new File(localpath + fileName);
// Clean up resources
System.out.printIn("\nPress the Enter key to begin clean up");
system.console().readLine();
nttps:/leam microsotcomlen-uslazuelstorago/olobsistorage-quicksta- blobs java7tabs=powershel%s2Cmanaged-identiy'2Croles-azure-portali.... 13/16‘y22124, 512 PM (Quickstart Azure Blob Storage library - Java | MirosoM Learn
system.out.printin( “Deleting blob container...")3
blobContainerClient.delete();
system.out.printIn("Deleting the local source and downloaded files..
localFile.delete();
downloadedFile.delete();
System.out. print1n("Done");
To learn more about deleting a container, and to explore more code samples, see Delete
and restore a blob container with Java.
Run the code
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
1. Navigate to the directory containing the pon.xnl file and compile the project by
using the following svn command:
Console
vn compile
2. Package the compiled code in its distributable format:
Console
mmvn package
3. Run the following nva command to execute the app:
Console
mvn exec: Java -D exec.mainClass=com.blobs.quickstart.App -D
exec. cleanupDaemonThreads=false
To simplify the run step, you can add exec-naven-plugin to pon.xnl and configure as
shown below:
nttps:/leam microsot.comlen-us/azurelstorage/olobsistorage-quickstar- blobs java7tabs-powershel%2Cmanaged-identiy'2Croles-azure-portali.... 14/16‘2124, 5:12 PM (Quickstart: Azure Blob Storage library - Java | Microsoft Le
XML
org. codehaus .mojo
exec-maven-plugin
1.4.8
com. blobs quickstart .App
false
With this configuration, you can execute the app with the following command:
Console
fvn exec: java
The output of the app is similar to the following example (UUID values omitted for
readability):
output
Azure Blob Storage - Java quickstart sample
Uploading to Blob storage as blob
https: //mystorageacct .blob. core.windows net /quickstartblobsUUID/quickstartUUID.
txt
Listing blobs.
quickstartUUID. txt
Downloading blob to
«/data/quickstartUUTDDOWNLOAD. txt
Press the Enter key to begin clean up
Deleting blob container...
Deleting the local source and downloaded files.
Done
Before you begin the cleanup process, check your data folder for the two files. You can
compare them and observe that they're identical
nttps:/leam microsotcomlen-uslazuelstorage/olobsistorage-quickstat-blbs java7tabs-powershel%s2Cmanaged-identiy'2Croles-azure-portali.... 15/16sa, sm Cuca: Az Bob Soap ray -Joa| rosa Lean
Clean up resources
After you've verified the files and finished testing, press the Enter key to delete the test files
along with the container you created in the storage account. You can also use Azure CLI to
delete resources
Next steps
In this quickstart, you learned how to upload, download, and list blobs using Java.
To see Blob storage sample apps, continue to:
[sere tb torge rary orn soe]
* To learn more, see the Azure Blob Storage client libraries for Java.
* For tutorials, samples, quickstarts, and other documentation, visit Azure for Java
developers
nttps:/leam microsotcomlen-uslazurelstorage/olobsistorage-quickstat-blbs java7tabs-powershel%s2Cmanaged-identiy'2Croles-azure-portali.... 16/16