Muokkaa

Jaa


Develop Java applications that use Azure Files

Learn the basics developing Java applications that use Azure Files to store data. Create a console application and learn basic actions using Azure Files APIs:

  • Create and delete Azure file shares
  • Create and delete directories
  • Enumerate files and directories in an Azure file share
  • Upload, download, and delete a file

Tip

Check out the Azure Storage code samples repository

For easy-to-use end-to-end Azure Storage code samples that you can download and run, please check out our list of Azure Storage Samples.

Applies to

File share type SMB NFS
Standard file shares (GPv2), LRS/ZRS Yes No
Standard file shares (GPv2), GRS/GZRS Yes No
Premium file shares (FileStorage), LRS/ZRS Yes No

Create a Java application

To build the samples, you'll need the Java Development Kit (JDK) and the Azure Storage SDK for Java. You'll also need an Azure storage account.

Set up your application to use Azure Files

To use the Azure Files APIs, add the following code to the top of the Java file from where you intend to access Azure Files.

// Include the following imports to use Azure Files APIs
import com.azure.storage.file.share.*;

Set up an Azure storage connection string

To use Azure Files, you need to connect to your Azure storage account. Configure a connection string and use it to connect to your storage account. Define a static variable to hold the connection string.

Replace <storage_account_name> and <storage_account_key> with the actual values for your storage account.

// Define the connection-string.
// Replace the values, including <>, with
// the values from your storage account.
public static final String connectStr = 
   "DefaultEndpointsProtocol=https;" +
   "AccountName=<storage_account_name>;" +
   "AccountKey=<storage_account_key>";

Access an Azure file share

To access Azure Files, create a ShareClient object. Use the ShareClientBuilder class to build a new ShareClient object.

ShareClient shareClient = new ShareClientBuilder()
    .connectionString(connectStr).shareName(shareName)
    .buildClient();

Create a file share

All files and directories in Azure Files are stored in a container called a share.

The ShareClient.create method throws an exception if the share already exists. Put the call to create in a try/catch block and handle the exception.

public static Boolean createFileShare(String connectStr, String shareName)
{
    try
    {
        ShareClient shareClient = new ShareClientBuilder()
            .connectionString(connectStr).shareName(shareName)
            .buildClient();

        shareClient.create();
        return true;
    }
    catch (Exception e)
    {
        System.out.println("createFileShare exception: " + e.getMessage());
        return false;
    }
}

Delete a file share

The following sample code deletes a file share.

Delete a share by calling the ShareClient.delete method.

public static Boolean deleteFileShare(String connectStr, String shareName)
{
    try
    {
        ShareClient shareClient = new ShareClientBuilder()
            .connectionString(connectStr).shareName(shareName)
            .buildClient();

        shareClient.delete();
        return true;
    }
    catch (Exception e)
    {
        System.out.println("deleteFileShare exception: " + e.getMessage());
        return false;
    }
}

Create a directory

Organize storage by putting files inside subdirectories instead of having all of them in the root directory.

The following code creates a directory by calling ShareDirectoryClient.create. The example method returns a Boolean value indicating if it successfully created the directory.

public static Boolean createDirectory(String connectStr, String shareName,
                                        String dirName)
{
    try
    {
        ShareDirectoryClient dirClient = new ShareFileClientBuilder()
             .connectionString(connectStr).shareName(shareName)
             .resourcePath(dirName)
             .buildDirectoryClient();

        dirClient.create();
        return true;
    }
    catch (Exception e)
    {
        System.out.println("createDirectory exception: " + e.getMessage());
        return false;
    }
}

Delete a directory

Deleting a directory is a straightforward task. You can't delete a directory that still contains files or subdirectories.

The ShareDirectoryClient.delete method throws an exception if the directory doesn't exist or isn't empty. Put the call to delete in a try/catch block and handle the exception.

public static Boolean deleteDirectory(String connectStr, String shareName,
                                        String dirName)
{
    try
    {
        ShareDirectoryClient dirClient = new ShareFileClientBuilder()
             .connectionString(connectStr).shareName(shareName)
             .resourcePath(dirName)
             .buildDirectoryClient();

        dirClient.delete();
        return true;
    }
    catch (Exception e)
    {
        System.out.println("deleteDirectory exception: " + e.getMessage());
        return false;
    }
}

Enumerate files and directories in an Azure file share

Get a list of files and directories by calling ShareDirectoryClient.listFilesAndDirectories. The method returns a list of ShareFileItem objects on which you can iterate. The following code lists files and directories inside the directory specified by the dirName parameter.

public static Boolean enumerateFilesAndDirs(String connectStr, String shareName,
                                                String dirName)
{
    try
    {
        ShareDirectoryClient dirClient = new ShareFileClientBuilder()
             .connectionString(connectStr).shareName(shareName)
             .resourcePath(dirName)
             .buildDirectoryClient();

        dirClient.listFilesAndDirectories().forEach(
            fileRef -> System.out.printf("Resource: %s\t Directory? %b\n",
            fileRef.getName(), fileRef.isDirectory())
        );

        return true;
    }
    catch (Exception e)
    {
        System.out.println("enumerateFilesAndDirs exception: " + e.getMessage());
        return false;
    }
}

Upload a file

Learn how to upload a file from local storage.

The following code uploads a local file to Azure Files by calling the ShareFileClient.uploadFromFile method. The following example method returns a Boolean value indicating if it successfully uploaded the specified file.

public static Boolean uploadFile(String connectStr, String shareName,
                                    String dirName, String fileName)
{
    try
    {
        ShareDirectoryClient dirClient = new ShareFileClientBuilder()
             .connectionString(connectStr).shareName(shareName)
             .resourcePath(dirName)
             .buildDirectoryClient();

        ShareFileClient fileClient = dirClient.getFileClient(fileName);
        fileClient.create(1024);
        fileClient.uploadFromFile(fileName);
        return true;
    }
    catch (Exception e)
    {
        System.out.println("uploadFile exception: " + e.getMessage());
        return false;
    }
}

Download a file

One of the more frequent operations is to download files from an Azure file share.

The following example downloads the specified file to the local directory specified in the destDir parameter. The example method makes the downloaded filename unique by prepending the date and time.

public static Boolean downloadFile(String connectStr, String shareName,
                                    String dirName, String destDir,
                                        String fileName)
{
    try
    {
        ShareDirectoryClient dirClient = new ShareFileClientBuilder()
             .connectionString(connectStr).shareName(shareName)
             .resourcePath(dirName)
             .buildDirectoryClient();

        ShareFileClient fileClient = dirClient.getFileClient(fileName);

        // Create a unique file name
        String date = new java.text.SimpleDateFormat("yyyyMMdd-HHmmss").format(new java.util.Date());
        String destPath = destDir + "/"+ date + "_" + fileName;

        fileClient.downloadToFile(destPath);
        return true;
    }
    catch (Exception e)
    {
        System.out.println("downloadFile exception: " + e.getMessage());
        return false;
    }
}

Delete a file

Another common Azure Files operation is file deletion.

The following code deletes the specified file specified. First, the example creates a ShareDirectoryClient based on the dirName parameter. Then, the code gets a ShareFileClient from the directory client, based on the fileName parameter. Finally, the example method calls ShareFileClient.delete to delete the file.

public static Boolean deleteFile(String connectStr, String shareName,
                                    String dirName, String fileName)
{
    try
    {
        ShareDirectoryClient dirClient = new ShareFileClientBuilder()
             .connectionString(connectStr).shareName(shareName)
             .resourcePath(dirName)
             .buildDirectoryClient();

        ShareFileClient fileClient = dirClient.getFileClient(fileName);
        fileClient.delete();
        return true;
    }
    catch (Exception e)
    {
        System.out.println("deleteFile exception: " + e.getMessage());
        return false;
    }
}

Next steps

If you would like to learn more about other Azure storage APIs, follow these links.

For related code samples using deprecated Java version 8 SDKs, see Code samples using Java version 8.