Quickstart: Manage blobs with Java v8 SDK

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

Prerequisites

  • An Azure account with an active subscription. Create an account for free.
  • An Azure Storage business relationship. Create a storage account.
  • An IDE that has Maven integration. This guide uses Eclipse with the "Eclipse IDE for Java Developers" configuration.

Download the sample application

The sample application is a basic console application.

Apply git to download a copy of the application to your development environment.

              git clone https://github.com/Azure-Samples/storage-blobs-java-quickstart.git                          

This command clones the repository to your local git folder. To open up the project, launch Eclipse and close the Welcome screen. Select File and then Open Projects from File Arrangement. Brand certain Detect and configure project natures is checked. Select Directory so navigate to where you lot stored the cloned repository. Inside the cloned repository, select the blobAzureApp binder. Make certain the blobAzureApp project appears as an Eclipse projection, so select Finish.

Once the project completes importing, open AzureApp.java (located in blobQuickstart.blobAzureApp within of src/main/java), and replace the accountname and accountkey inside of the storageConnectionString string. And then run the application. Specific instructions for completing these tasks are described in the following sections.

Re-create your credentials from the Azure portal

The sample awarding needs to authenticate admission to your storage account. To cosign, add your storage account credentials to the awarding as a connection string. View your storage account credentials by post-obit these steps:

  1. Sign in to the Azure portal.

  2. Locate your storage account.

  3. In the Settings section of the storage account overview, select Access keys. Here, you lot tin view your account access keys and the complete connection string for each cardinal.

  4. Observe the Connection cord value nether key1, and select the Copy push to copy the connection string. You will add the connection cord value to an environment variable in the adjacent footstep.

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

Configure your storage connection string

In the application, you lot must provide the connection cord for your storage business relationship. Open the AzureApp.Java file. Find the storageConnectionString variable and paste the connexion string value that you copied in the previous department. Your storageConnectionString variable should look similar to the following code instance:

              public static final String storageConnectionString = "DefaultEndpointsProtocol=https;" + "AccountName=<business relationship-proper noun>;" + "AccountKey=<business relationship-key>";                          

Run the sample

This sample application creates a test file in your default directory (C:\Users<user>\AppData\Local\Temp, for Windows users), uploads it to Blob storage, lists the blobs in the container, so downloads the file with a new name then you can compare the sometime and new files.

Run the sample using Maven at the command line. Open a shell and navigate to blobAzureApp inside of your cloned directory. Then enter mvn compile exec:java.

The following example shows the output if you were to run the application on Windows.

              Azure Hulk storage quick start sample Creating container: quickstartcontainer Creating a sample file at: C:\Users\<user>\AppData\Local\Temp\sampleFile514658495642546986.txt Uploading the sample file URI of blob is: https://myexamplesacct.blob.core.windows.internet/quickstartcontainer/sampleFile514658495642546986.txt The program has completed successfully. Press the 'Enter' primal while in the panel to delete the sample files, example container, and leave the awarding.  Deleting the container Deleting the source, and downloaded files                          

Before you continue, check your default directory (C:\Users<user>\AppData\Local\Temp, for Windows users) for the sample file. Re-create the URL for the hulk out of the console window and paste it into a browser to view the contents of the file in Blob storage. If yous compare the sample file in your directory with the contents stored in Blob storage, yous will encounter that they are the same.

Annotation

Y'all can also use a tool such as the Azure Storage Explorer to view the files in Hulk storage. Azure Storage Explorer is a gratuitous cross-platform tool that allows you to access your storage account information.

After you've verified the files, printing the Enter key to complete the demo and delete the test files. Now that y'all know what the sample does, open the AzureApp.coffee file to expect at the lawmaking.

Sympathize the sample lawmaking

Next, we walk through the sample code so that yous can understand how it works.

Become references to the storage objects

The start matter to practice is create the references to the objects used to access and manage Blob storage. These objects build on each other -- each is used past the next ane in the list.

  • Create an instance of the CloudStorageAccount object pointing to the storage account.

    The CloudStorageAccount object is a representation of your storage account and it allows you to fix and access storage business relationship properties programmatically. Using the CloudStorageAccount object you lot can create an instance of the CloudBlobClient, which is necessary to access the blob service.

  • Create an instance of the CloudBlobClient object, which points to the Blob service in your storage account.

    The CloudBlobClient provides you a betoken of admission to the hulk service, allowing you lot to set and access Hulk storage properties programmatically. Using the CloudBlobClient you can create an instance of the CloudBlobContainer object, which is necessary to create containers.

  • Create an instance of the CloudBlobContainer object, which represents the container you are accessing. Use containers to organize your blobs like y'all use folders on your computer to organize your files.

    In one case you lot accept the CloudBlobContainer, you tin can create an instance of the CloudBlockBlob object that points to the specific blob you're interested in, and perform an upload, download, copy, or other performance.

Create a container

In this section, you create an example of the objects, create a new container, and and then set permissions on the container so the blobs are public and tin be accessed with just a URL. The container is chosen quickstartcontainer.

This example uses CreateIfNotExists because nosotros want to create a new container each fourth dimension the sample is run. In a product surround, where you utilise the same container throughout an application, it'south meliorate practise to only call CreateIfNotExists in one case. Alternatively, you can create the container ahead of time so you don't need to create information technology in the code.

              // Parse the connection string and create a hulk client to collaborate with Blob storage storageAccount = CloudStorageAccount.parse(storageConnectionString); blobClient = storageAccount.createCloudBlobClient(); container = blobClient.getContainerReference("quickstartcontainer");  // Create the container if information technology does non exist with public admission. Arrangement.out.println("Creating container: " + container.getName()); container.createIfNotExists(BlobContainerPublicAccessType.CONTAINER, new BlobRequestOptions(), new OperationContext());                          

Upload blobs to the container

To upload a file to a block blob, become a reference to the blob in the target container. Once y'all have the blob reference, yous tin upload data to it past using CloudBlockBlob.Upload. This operation creates the blob if it doesn't already exist, or overwrites the blob if it already exists.

The sample lawmaking creates a local file to be used for the upload and download, storing the file to exist uploaded as source and the name of the blob in blob. The following example uploads the file to your container chosen quickstartcontainer.

              //Creating a sample file sourceFile = File.createTempFile("sampleFile", ".txt"); Organisation.out.println("Creating a sample file at: " + sourceFile.toString()); Writer output = new BufferedWriter(new FileWriter(sourceFile)); output.write("How-do-you-do Azure!"); output.shut();  //Getting a blob reference CloudBlockBlob hulk = container.getBlockBlobReference(sourceFile.getName());  //Creating blob and uploading file to it Arrangement.out.println("Uploading the sample file "); blob.uploadFromFile(sourceFile.getAbsolutePath());                          

There are several upload methods including upload, uploadBlock, uploadFullBlob, uploadStandardBlobTier, and uploadText which yous can utilise with Blob storage. For example, if you lot accept a string, you tin can use the UploadText method rather than the Upload method.

Block blobs can be whatsoever blazon of text or binary file. Folio blobs are primarily used for the VHD files that back IaaS VMs. Use suspend blobs for logging, such as when you want to write to a file and so keep adding more data. Well-nigh objects stored in Hulk storage are block blobs.

List the blobs in a container

You can get a list of files in the container using CloudBlobContainer.ListBlobs. The following lawmaking retrieves the list of blobs, then loops through them, showing the URIs of the blobs found. You tin can copy the URI from the command window and paste it into a browser to view the file.

              //List contents of container for (ListBlobItem blobItem : container.listBlobs()) {     Organization.out.println("URI of blob is: " + blobItem.getUri()); }                          

Download blobs

Download blobs to your local disk using CloudBlob.DownloadToFile.

The following code downloads the blob uploaded in a previous section, adding a suffix of "_DOWNLOADED" to the blob proper noun so y'all can see both files on local disk.

              // Download hulk. In about cases, you would take to retrieve the reference // to cloudBlockBlob hither. Even so, nosotros created that reference earlier, and // haven't changed the hulk we're interested in, so we can reuse it. // Here we are creating a new file to download to. Alternatively you tin can also pass in the path as a cord into downloadToFile method: hulk.downloadToFile("/path/to/new/file"). downloadedFile = new File(sourceFile.getParentFile(), "downloadedFile.txt"); blob.downloadToFile(downloadedFile.getAbsolutePath());                          

Make clean up resources

If you no longer need the blobs that you take uploaded, you tin can delete the unabridged container using CloudBlobContainer.DeleteIfExists. This method too deletes the files in the container.

              try { if(container != zero)     container.deleteIfExists(); } catch (StorageException ex) { System.out.println(Cord.format("Service fault. Http code: %d and error code: %south", ex.getHttpStatusCode(), ex.getErrorCode())); }  System.out.println("Deleting the source, and downloaded files");  if(downloadedFile != null) downloadedFile.deleteOnExit();  if(sourceFile != null) sourceFile.deleteOnExit();                          

Next steps

In this article, you learned how to transfer files between a local disk and Azure Blob storage using Java. To learn more than nigh working with Java, continue to our GitHub source lawmaking repository.