使用 Java 针对 Azure 文件进行开发Develop for Azure Files with Java

了解开发使用 Azure 文件存储来存储数据的 Java 应用程序的基础知识。Learn the basics developing Java applications that use Azure Files to store data. 使用 Azure 文件存储 API 创建控制台应用程序并了解基本操作:Create a console application and learn basic actions using Azure Files APIs:

  • 创建和删除 Azure 文件共享Create and delete Azure file shares
  • 创建和删除目录Create and delete directories
  • 枚举 Azure 文件共享中的文件和目录Enumerate files and directories in an Azure file share
  • 上传、下载和删除文件Upload, download, and delete a file

提示

查看 Azure 存储代码示例存储库Check out the Azure Storage code samples repository

如需易用且能够下载和运行的端到端 Azure 存储代码示例,请查看我们的 Azure 存储示例列表。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.

创建 Java 应用程序Create a Java application

若要生成示例,需要 Java 开发工具包 (JDK) 和适用于 Java 的 Azure 存储 SDKTo build the samples, you'll need the Java Development Kit (JDK) and the Azure Storage SDK for Java. 此外,应该已经创建了一个 Azure 存储帐户。You should also have created an Azure storage account.

设置应用程序以使用 Azure 文件Set up your application to use Azure Files

若要使用 Azure 文件存储 API,请将以下代码添加到要通过其访问 Azure 文件存储的 Java 文件的顶部。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.*;

设置 Azure 存储连接字符串Set up an Azure storage connection string

要使用 Azure 文件,需要连接到 Azure 存储帐户。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.

<storage_account_name><storage_account_key> 替换为存储帐户的实际值。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>"; +
   "EndpointSuffix=core.Chinacloudapi.cn";

访问 Azure 文件存储Access Azure Files storage

若要访问 Azure 文件存储,请创建一个 ShareClient 对象。To access Azure Files, create a ShareClient object. 使用 ShareClientBuilder 类生成新的 ShareClient 对象。Use the ShareClientBuilder class to build a new ShareClient object.

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

创建文件共享Create a file share

Azure 文件存储中的所有文件和目录都存储在名为共享的容器内。All files and directories in Azure Files are stored in a container called a share.

如果共享已经存在,则 ShareClient.create 方法将引发异常。The ShareClient.create method throws an exception if the share already exists. 将对 create 的调用置于 try/catch 块中并处理异常。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.

通过调用 ShareClient.delete 方法删除共享。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.

以下代码通过调用 ShareDirectoryClient.create 创建目录。The following code creates a directory by calling ShareDirectoryClient.create. 示例方法返回一个 Boolean 值,该值指示它是否成功创建了目录。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.

如果目录不存在或不为空,则 ShareDirectoryClient.delete 方法将引发异常。The ShareDirectoryClient.delete method throws an exception if the directory doesn't exist or isn't empty. 将对 delete 的调用置于 try/catch 块中并处理异常。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;
    }
}

枚举 Azure 文件共享中的文件和目录Enumerate files and directories in an Azure file share

通过调用 ShareDirectoryClient.listFilesAndDirectories 获取文件和目录的列表。Get a list of files and directories by calling ShareDirectoryClient.listFilesAndDirectories. 该方法会返回可循环访问的 ShareFileItem 对象的列表。The method returns a list of ShareFileItem objects on which you can iterate. 以下代码将列出 dirName 参数指定的目录内的文件和目录。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.

以下代码通过调用 ShareFileClient.uploadFromFile 方法将本地文件上传到 Azure 文件存储。The following code uploads a local file to Azure File storage by calling the ShareFileClient.uploadFromFile method. 以下示例方法返回一个 Boolean 值,该值指示它是否成功上传了指定的文件。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

较常见的操作之一是从 Azure 文件存储下载文件。One of the more frequent operations is to download files from Azure Files storage.

以下示例将指定文件下载到 destDir 参数中指定的本地目录。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

另一项常见的 Azure 文件操作是删除文件。Another common Azure Files operation is file deletion.

以下代码将删除指定文件。The following code deletes the specified file specified. 首先,该示例基于 dirName 参数创建一个 ShareDirectoryClientFirst, the example creates a ShareDirectoryClient based on the dirName parameter. 然后,代码根据 fileName 参数从目录客户端获取 ShareFileClientThen, the code gets a ShareFileClient from the directory client, based on the fileName parameter. 最后,示例方法调用 ShareFileClient.delete 来删除文件。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

如果还想更多地了解其他 Azure 存储 API,请点击以下链接。If you would like to learn more about other Azure storage APIs, follow these links.