Quickstart: Manage blobs with Java v12 SDK

In this quickstart, you learn to manage blobs past using Java. Blobs are objects that can concord large amounts of text or binary data, including images, documents, streaming media, and archive information. You'll upload, download, and list blobs, and you'll create and delete containers.

Additional resources:

  • API reference documentation
  • Library source lawmaking
  • Package (Maven)
  • Samples

Prerequisites

  • An Azure business relationship with an active subscription. Create an business relationship for free.
  • An Azure Storage account. Create a storage account.
  • Coffee 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 v12 for Java.

Create the project

Create a Java awarding named blob-quickstart-v12.

  1. In a panel window (such as cmd, PowerShell, or Bash), use Maven to create a new console app with the name blob-quickstart-v12. Blazon the post-obit mvn command to create a "Hi world!" Coffee project.

    • PowerShell
    • Bash
                          mvn archetype:generate `     --define interactiveMode=n `     --ascertain groupId=com.blobs.quickstart `     --define artifactId=hulk-quickstart-v12 `     --define archetypeArtifactId=maven-archetype-quickstart `     --define archetypeVersion=one.4                                          
  2. The 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 Projection (No POM) ane [INFO] --------------------------------[ pom ]--------------------------------- [INFO] [INFO] >>> maven-archetype-plugin:3.one.two:generate (default-cli) > generate-sources @ standalone-pom >>> [INFO] [INFO] <<< maven-classic-plugin:3.1.ii:generate (default-cli) < generate-sources @ standalone-pom <<< [INFO] [INFO] [INFO] --- maven-archetype-plugin:3.1.two:generate (default-cli) @ standalone-pom --- [INFO] Generating project in Batch way [INFO] ---------------------------------------------------------------------------- [INFO] Using post-obit parameters for creating project from Archetype: maven-archetype-quickstart:1.four [INFO] ---------------------------------------------------------------------------- [INFO] Parameter: groupId, Value: com.blobs.quickstart [INFO] Parameter: artifactId, Value: blob-quickstart-v12 [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: packet, Value: com.blobs.quickstart [INFO] Parameter: groupId, Value: com.blobs.quickstart [INFO] Parameter: artifactId, Value: blob-quickstart-v12 [INFO] Projection created from Classic in dir: C:\QuickStarts\blob-quickstart-v12 [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total fourth dimension:  7.056 s [INFO] Finished at: 2019-10-23T11:09:21-07:00 [INFO] ------------------------------------------------------------------------     ```                                  
  3. Switch to the newly created blob-quickstart-v12 folder.

                      cd blob-quickstart-v12                                  
  4. In side the blob-quickstart-v12 directory, create some other directory called data. This is where the blob data files will be created and stored.

                      mkdir information                                  

Install the packet

Open up the pom.xml file in your text editor. Add the post-obit dependency element to the group of dependencies.

              <dependency>     <groupId>com.azure</groupId>     <artifactId>azure-storage-blob</artifactId>     <version>12.13.0</version> </dependency>                          

Ready the app framework

From the project directory:

  1. Navigate to the /src/main/coffee/com/blobs/quickstart directory
  2. Open the App.coffee file in your editor
  3. Delete the System.out.println("Hullo world!"); statement
  4. Add together import directives

Here's the code:

              package com.blobs.quickstart;  /**  * Azure hulk storage v12 SDK quickstart  */ import com.azure.storage.blob.*; import com.azure.storage.blob.models.*; import coffee.io.*;  public class App {     public static void main( String[] args ) throws IOException     {     } }                          

Re-create your credentials from the Azure portal

When the sample application makes a request to Azure Storage, information technology must be authorized. To qualify a asking, add together your storage account credentials to the application every bit a connection string. To view your storage business relationship credentials, follow these steps:

  1. Sign in to the Azure portal.

  2. Locate your storage business relationship.

  3. In the storage account menu pane, nether Security + networking, select Access keys. Here, you can view the account access keys and the complete connection string for each fundamental.

    Screenshot that shows where the access key settings are in the Azure portal

  4. In the Access keys pane, select Show keys.

  5. In the key1 section, locate the Connection string value. Select the Copy to clipboard icon to copy the connection string. You lot'll add the connexion cord value to an environs variable in the next section.

    Screenshot showing how to copy a connection string from the Azure portal

Configure your storage connection string

Afterwards you copy the connection string, write it to a new environment variable on the local machine running the application. To set the environs variable, open up a console window, and follow the instructions for your operating system. Supersede <yourconnectionstring> with your actual connection string.

  • Windows
  • Linux and macOS
                  setx AZURE_STORAGE_CONNECTION_STRING "<yourconnectionstring>"                                  

Afterward yous add the environment variable in Windows, you must start a new instance of the command window.

Restart programs

After you add the surround variable, restart whatever running programs that will need to read the surround variable. For example, restart your development environment or editor before you continue.

Object model

Azure Blob Storage is optimized for storing massive amounts of unstructured information. Unstructured data is data that does not adhere to a particular data model or definition, such as text or binary data. Blob storage offers three types of resource:

  • The storage account
  • A container in the storage account
  • A blob in the container

The post-obit diagram shows the relationship betwixt these resources.

Diagram of Blob storage architecture

Employ the following Java classes to interact with these resources:

  • BlobServiceClient: The BlobServiceClient class allows you to dispense Azure Storage resources and blob containers. The storage account provides the top-level namespace for the Blob service.
  • BlobServiceClientBuilder: The BlobServiceClientBuilder course provides a fluent architect API to help aid the configuration and instantiation of BlobServiceClient objects.
  • BlobContainerClient: The BlobContainerClient class allows you to dispense Azure Storage containers and their blobs.
  • BlobClient: The BlobClient grade allows y'all to manipulate Azure Storage blobs.
  • BlobItem: The BlobItem class represents individual blobs returned from a telephone call to listBlobs.

Code examples

These case code snippets show y'all how to perform the following with the Azure Blob Storage customer library for Java:

  • Become the connexion string
  • Create a container
  • Upload blobs to a container
  • List the blobs in a container
  • Download blobs
  • Delete a container

Get the connection cord

The lawmaking below retrieves the connection string for the storage account from the surround variable created in the Configure your storage connection string section.

Add this lawmaking inside the Main method:

              Organisation.out.println("Azure Blob Storage v12 - Java quickstart sample\n");  // Call back the connexion string for use with the application. The storage // connection string is stored in an environment variable on the machine // running the application called AZURE_STORAGE_CONNECTION_STRING. If the environment variable // is created subsequently the application is launched in a console or with // Visual Studio, the beat out or awarding needs to be airtight and reloaded // to take the environment variable into account. String connectStr = System.getenv("AZURE_STORAGE_CONNECTION_STRING");                          

Create a container

Decide on a name for the new container. The lawmaking below appends a UUID value to the container proper noun to ensure that it is unique.

Next, create an instance of the BlobContainerClient form, then call the create method to actually create the container in your storage account.

Add this code to the end of the Main method:

              // Create a BlobServiceClient object which will be used to create a container customer BlobServiceClient blobServiceClient = new BlobServiceClientBuilder().connectionString(connectStr).buildClient();  //Create a unique name for the container Cord containerName = "quickstartblobs" + java.util.UUID.randomUUID();  // Create the container and return a container client object BlobContainerClient containerClient = blobServiceClient.createBlobContainer(containerName);                          

Upload blobs to a container

The following code snippet:

  1. Creates a text file in the local information 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, merely will not overwrite it if information technology does.

Add together this code to the terminate of the Main method:

              // Create a local file in the ./data/ directory for uploading and downloading String localPath = "./data/"; String fileName = "quickstart" + java.util.UUID.randomUUID() + ".txt"; File localFile = new File(localPath + fileName);  // Write text to the file FileWriter writer = new FileWriter(localPath + fileName, true); author.write("Hi, Globe!"); writer.close();  // Get a reference to a blob BlobClient blobClient = containerClient.getBlobClient(fileName);  System.out.println("\nUploading to Hulk storage as blob:\n\t" + blobClient.getBlobUrl());  // Upload the blob blobClient.uploadFromFile(localPath + fileName);                          

List the blobs in a container

List the blobs in the container by calling the listBlobs method. In this case, only i blob has been added to the container, and then the listing operation returns only that one blob.

Add this lawmaking to the cease of the Main method:

              System.out.println("\nListing blobs...");  // List the blob(s) in the container. for (BlobItem blobItem : containerClient.listBlobs()) {     Organization.out.println("\t" + blobItem.getName()); }                          

Download blobs

Download the previously created blob past calling the downloadToFile method. The example code adds a suffix of "DOWNLOAD" to the file name so that you lot can see both files in local file organisation.

Add together this code to the stop of the Main method:

              // Download the blob to a local file // Append the string "DOWNLOAD" before the .txt extension so that you can meet both files. Cord downloadFileName = fileName.supercede(".txt", "DOWNLOAD.txt"); File downloadedFile = new File(localPath + downloadFileName);  System.out.println("\nDownloading blob to\n\t " + localPath + downloadFileName);  blobClient.downloadToFile(localPath + downloadFileName);                          

Delete a container

The following code cleans upwardly the resource the app created past removing the entire container using the delete method. It also deletes the local files created past the app.

The app pauses for user input past calling Organisation.console().readLine() before it deletes the blob, container, and local files. This is a good adventure to verify that the resources were created correctly, earlier they are deleted.

Add together this code to the finish of the Main method:

              // Clean up System.out.println("\nPress the Enter fundamental to brainstorm clean up"); System.panel().readLine();  System.out.println("Deleting blob container..."); containerClient.delete();  System.out.println("Deleting the local source and downloaded files..."); localFile.delete(); downloadedFile.delete();  System.out.println("Washed");                          

Run the code

This app creates a test file in your local binder and uploads it to Blob storage. The example then lists the blobs in the container and downloads the file with a new proper noun and so that you tin can compare the quondam and new files.

Navigate to the directory containing the pom.xml file and compile the project by using the post-obit mvn command.

              mvn compile                          

Then, build the package.

              mvn package                          

Run the following mvn command to execute the app.

              mvn exec:java -Dexec.mainClass="com.blobs.quickstart.App" -Dexec.cleanupDaemonThreads=false                          

The output of the app is like to the post-obit instance:

              Azure Blob Storage v12 - Java quickstart sample  Uploading to Hulk storage as hulk:         https://mystorageacct.blob.core.windows.net/quickstartblobsf9aa68a5-260e-47e6-bea2-2dcfcfa1fd9a/quickstarta9c3a53e-ae9d-4863-8b34-f3d807992d65.txt  List blobs...         quickstarta9c3a53e-ae9d-4863-8b34-f3d807992d65.txt  Downloading blob to         ./information/quickstarta9c3a53e-ae9d-4863-8b34-f3d807992d65DOWNLOAD.txt  Press the Enter key to begin clean up  Deleting blob container... Deleting the local source and downloaded files... Done                          

Before yous begin the clean upwardly process, cheque your data folder for the two files. You lot tin can open them and find that they are identical.

After you've verified the files, press the Enter key to delete the test files and cease the demo.

Adjacent steps

In this quickstart, you learned how to upload, download, and list blobs using Coffee.

To see Blob storage sample apps, go along to:

  • To learn more, meet the Azure SDK for Java.
  • For tutorials, samples, quickstarts, and other documentation, visit Azure for Java cloud developers.