Quickstart: Manage blobs with Java v8 SDK

In this quickstart, you learn to manage blobs by using Java. Blobs are objects that can hold large amounts of text or binary data, including images, documents, streaming media, and annal data. You'll upload, download, and list blobs. You'll besides create, set up permissions on, and delete containers.

Prerequisites

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

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

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

This command clones the repository to your local git folder. To open the project, launch Eclipse and close the Welcome screen. Select File then Open Projects from File Organisation. Make sure Detect and configure project natures is checked. Select Directory then navigate to where you stored the cloned repository. Inside the cloned repository, select the blobAzureApp folder. Make sure the blobAzureApp project appears as an Eclipse project, then select End.

One time 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. Then run the application. Specific instructions for completing these tasks are described in the post-obit sections.

Copy your credentials from the Azure portal

The sample application needs to authenticate access to your storage account. To authenticate, add your storage account credentials to the application as a connection string. View your storage account credentials past following 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 can view your account admission keys and the complete connection cord for each central.

  4. Find the Connexion string value under key1, and select the Copy push to copy the connection string. Yous will add together the connection string value to an surroundings variable in the side by side step.

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

Configure your storage connection cord

In the application, you must provide the connection cord for your storage account. Open up the AzureApp.Java file. Detect the storageConnectionString variable and paste the connection string value that y'all copied in the previous section. Your storageConnectionString variable should look like to the following code instance:

              public static concluding String storageConnectionString = "DefaultEndpointsProtocol=https;" + "AccountName=<account-proper name>;" + "AccountKey=<account-primal>";                          

Run the sample

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

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

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

              Azure Blob 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.net/quickstartcontainer/sampleFile514658495642546986.txt The programme has completed successfully. Printing the 'Enter' key while in the console to delete the sample files, example container, and get out the application.  Deleting the container Deleting the source, and downloaded files                          

Before you continue, cheque your default directory (C:\Users<user>\AppData\Local\Temp, for Windows users) for the sample file. Copy the URL for the blob out of the panel window and paste it into a browser to view the contents of the file in Blob storage. If you compare the sample file in your directory with the contents stored in Blob storage, you will come across that they are the same.

Notation

You tin can also apply a tool such equally the Azure Storage Explorer to view the files in Blob storage. Azure Storage Explorer is a free cross-platform tool that allows you to access your storage account information.

Later on you've verified the files, press the Enter key to complete the demo and delete the exam files. Now that yous know what the sample does, open the AzureApp.java file to look at the code.

Understand the sample code

Next, we walk through the sample lawmaking so that you can sympathize how it works.

Go references to the storage objects

The showtime affair to practise is create the references to the objects used to access and manage Hulk storage. These objects build on each other -- each is used past the next one 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 y'all to set and admission storage business relationship properties programmatically. Using the CloudStorageAccount object you can create an instance of the CloudBlobClient, which is necessary to admission the blob service.

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

    The CloudBlobClient provides you lot a signal of access to the blob service, assuasive you to ready and access Blob 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 lot are accessing. Apply containers to organize your blobs like you use folders on your computer to organize your files.

    Once you accept the CloudBlobContainer, y'all tin create an example of the CloudBlockBlob object that points to the specific blob you're interested in, and perform an upload, download, copy, or other operation.

Create a container

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

This example uses CreateIfNotExists considering we want to create a new container each fourth dimension the sample is run. In a product environs, where you use the same container throughout an application, it's better do to only phone call CreateIfNotExists once. Alternatively, y'all can create the container ahead of fourth dimension so yous don't need to create information technology in the code.

              // Parse the connection cord and create a blob customer to interact with Blob storage storageAccount = CloudStorageAccount.parse(storageConnectionString); blobClient = storageAccount.createCloudBlobClient(); container = blobClient.getContainerReference("quickstartcontainer");  // Create the container if information technology does not be with public access. System.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 hulk, get a reference to the blob in the target container. One time y'all have the blob reference, you can upload information to it by 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 be uploaded equally source and the proper name of the hulk in hulk. The following example uploads the file to your container called quickstartcontainer.

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

In that location are several upload methods including upload, uploadBlock, uploadFullBlob, uploadStandardBlobTier, and uploadText which you tin can apply with Blob storage. For example, if you have a string, y'all tin can utilise the UploadText method rather than the Upload method.

Block blobs can exist any type of text or binary file. Folio blobs are primarily used for the VHD files that back IaaS VMs. Employ append blobs for logging, such as when you want to write to a file so keep adding more than information. Most objects stored in Hulk storage are cake blobs.

List the blobs in a container

You can go a listing of files in the container using CloudBlobContainer.ListBlobs. The post-obit code retrieves the list of blobs, then loops through them, showing the URIs of the blobs found. You 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()) {     System.out.println("URI of hulk is: " + blobItem.getUri()); }                          

Download blobs

Download blobs to your local disk using CloudBlob.DownloadToFile.

The following lawmaking downloads the hulk uploaded in a previous section, adding a suffix of "_DOWNLOADED" to the hulk name then y'all can see both files on local deejay.

              // Download blob. In most cases, you would have to retrieve the reference // to cloudBlockBlob here. However, we created that reference earlier, and // haven't inverse the blob we're interested in, so we tin reuse it. // Hither nosotros are creating a new file to download to. Alternatively you can also pass in the path equally a string into downloadToFile method: blob.downloadToFile("/path/to/new/file"). downloadedFile = new File(sourceFile.getParentFile(), "downloadedFile.txt"); hulk.downloadToFile(downloadedFile.getAbsolutePath());                          

Clean upwards resource

If you no longer need the blobs that you lot take uploaded, y'all can delete the unabridged container using CloudBlobContainer.DeleteIfExists. This method as well deletes the files in the container.

              effort { if(container != null)     container.deleteIfExists(); } take hold of (StorageException ex) { System.out.println(String.format("Service error. Http lawmaking: %d and error lawmaking: %s", ex.getHttpStatusCode(), ex.getErrorCode())); }  System.out.println("Deleting the source, and downloaded files");  if(downloadedFile != zilch) downloadedFile.deleteOnExit();  if(sourceFile != cypher) sourceFile.deleteOnExit();                          

Next steps

In this commodity, y'all learned how to transfer files betwixt a local disk and Azure Blob storage using Java. To learn more about working with Java, keep to our GitHub source code repository.