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

提示

查看 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.

关于本教程About this tutorial

本教程将演示使用 Java 开发应用程序或服务的基础知识,这些应用程序或服务可以使用 Azure 文件来存储文件数据。This tutorial will demonstrate the basics of using Java to develop applications or services that use Azure Files to store file data. 在本教程中,我们将创建一个控制台应用程序,并演示如何通过 Java 和 Azure 文件执行基本操作:In this tutorial, we will create a console application and show how to perform basic actions with Java and Azure Files:

  • 创建和删除 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 文件可以通过 SMB 进行访问,因此可以编写应用程序,通过标准的 Java I/O 类来访问 Azure 文件共享。Because Azure Files may be accessed over SMB, it is possible to write applications that access the Azure file share using the standard Java I/O classes. 本文介绍如何编写使用 Azure 存储 Java SDK 的应用程序,该 SDK 使用 Azure 文件 REST API 与 Azure 文件通信。This article will describe how to write applications that use the Azure Storage Java SDK, which uses the Azure Files REST API to talk to Azure Files.

创建 Java 应用程序Create a Java application

若要生成示例,需要 Java 开发工具包 (JDK) 和用于 Java 的 Azure 存储 SDKTo build the samples, you will 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,请将下列语句添加到要通过其来访问存储服务的 Java 文件的顶部:To use the Azure storage APIs, add the following statement to the top of the Java file where you intend to access the storage service from.

// Include the following imports to use blob APIs.
import com.microsoft.azure.storage.*;
import com.microsoft.azure.storage.file.*;

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

要使用 Azure 文件,需要连接到 Azure 存储帐户。To use Azure Files, you need to connect to your Azure storage account. 第一步是配置连接字符串,我们会使用该字符串连接到存储帐户。The first step would be to configure a connection string, which we'll use to connect to your storage account. 为此,我们需要定义一个静态变量。Let's define a static variable to do that.

// Configure the connection-string with your values
public static final String storageConnectionString =
    "DefaultEndpointsProtocol=http;" +
    "AccountName=your_storage_account_name;" +
    "AccountKey=your_storage_account_key;" +
    "EndpointSuffix=core.Chinacloudapi.cn";

备注

将 your_storage_account_name 和 your_storage_account_key 替换为存储帐户的实际值。Replace your_storage_account_name and your_storage_account_key with the actual values for your storage account.

连接到 Azure 存储帐户Connecting to an Azure storage account

要连接到存储帐户,则需要使用 CloudStorageAccount 对象,以便将连接字符串传递到 parse 方法。To connect to your storage account, you need to use the CloudStorageAccount object, passing a connection string to its parse method.

// Use the CloudStorageAccount object to connect to your storage account
try {
    CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString);
} catch (InvalidKeyException invalidKey) {
    // Handle the exception
}

CloudStorageAccount.parse 会引发 InvalidKeyException,因此需将其置于 try/catch 块内。CloudStorageAccount.parse throws an InvalidKeyException so you'll need to put it inside a try/catch block.

创建 Azure 文件共享Create an Azure file share

Azure 文件中的所有文件和目录都位于名为 Share 的容器内 。All files and directories in Azure Files reside in a container called a Share. 存储帐户可以拥有无数的共享,只要帐户容量允许。Your storage account can have as many shares as your account capacity allows. 要获得共享及其内容的访问权限,需要使用 Azure 文件客户端。To obtain access to a share and its contents, you need to use an Azure Files client.

// Create the Azure Files client.
CloudFileClient fileClient = storageAccount.createCloudFileClient();

使用 Azure 文件客户端可以获取对共享的引用。Using the Azure Files client, you can then obtain a reference to a share.

// Get a reference to the file share
CloudFileShare share = fileClient.getShareReference("sampleshare");

实际创建共享时,请使用 CloudFileShare 对象的 createIfNotExists方法。To actually create the share, use the createIfNotExists method of the CloudFileShare object.

if (share.createIfNotExists()) {
    System.out.println("New share created");
}

而在目前,share 保留对名为 sampleshare 的共享的引用。At this point, share holds a reference to a share named sampleshare.

删除 Azure 文件共享Delete an Azure file share

删除共享时,可针对 CloudFileShare 对象调用 deleteIfExists 方法。Deleting a share is done by calling the deleteIfExists method on a CloudFileShare object. 以下是具有此类功能的示例代码。Here's sample code that does that.

try
{
    // Retrieve storage account from connection-string.
    CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString);

    // Create the file client.
   CloudFileClient fileClient = storageAccount.createCloudFileClient();

   // Get a reference to the file share
   CloudFileShare share = fileClient.getShareReference("sampleshare");

   if (share.deleteIfExists()) {
       System.out.println("sampleshare deleted");
   }
} catch (Exception e) {
    e.printStackTrace();
}

创建目录Create a directory

也可以将文件置于子目录中,不必将其全部置于根目录中,以便对存储进行有效的组织。You can also organize storage by putting files inside subdirectories instead of having all of them in the root directory. 使用 Azure 文件可以创建帐户允许的任意数目的目录。Azure Files allows you to create as many directories as your account will allow. 以下代码会在根目录下创建名为 sampledir 的子目录。The code below will create a subdirectory named sampledir under the root directory.

//Get a reference to the root directory for the share.
CloudFileDirectory rootDir = share.getRootDirectoryReference();

//Get a reference to the sampledir directory
CloudFileDirectory sampleDir = rootDir.getDirectoryReference("sampledir");

if (sampleDir.createIfNotExists()) {
    System.out.println("sampledir created");
} else {
    System.out.println("sampledir already exists");
}

删除目录Delete a directory

删除目录很简单,但需注意的是,不能删除仍然包含文件或其他目录的目录。Deleting a directory is a straightforward task, although it should be noted that you cannot delete a directory that still contains files or other directories.

// Get a reference to the root directory for the share.
CloudFileDirectory rootDir = share.getRootDirectoryReference();

// Get a reference to the directory you want to delete
CloudFileDirectory containerDir = rootDir.getDirectoryReference("sampledir");

// Delete the directory
if ( containerDir.deleteIfExists() ) {
    System.out.println("Directory deleted");
}

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

可以轻松获取共享中文件和目录的列表,只需针对 CloudFileDirectory 引用调用 listFilesAndDirectories 即可。Obtaining a list of files and directories within a share is easily done by calling listFilesAndDirectories on a CloudFileDirectory reference. 该方法将返回可以对其进行循环访问的 ListFileItem 对象的列表。The method returns a list of ListFileItem objects which you can iterate on. 例如,下面的代码将列出根目录中的文件和目录。As an example, the following code will list files and directories inside the root directory.

//Get a reference to the root directory for the share.
CloudFileDirectory rootDir = share.getRootDirectoryReference();

for ( ListFileItem fileItem : rootDir.listFilesAndDirectories() ) {
    System.out.println(fileItem.getUri());
}

上传文件Upload a file

在本部分,学习如何将文件从本地存储上传到共享所在的根目录。In this section, you'll learn how to upload a file from local storage onto the root directory of a share.

上传文件的第一步是获取对文件所在的目录的引用。The first step in uploading a file is to obtain a reference to the directory where it should reside. 为此,需要调用共享对象的 getRootDirectoryReference 方法。You do this by calling the getRootDirectoryReference method of the share object.

//Get a reference to the root directory for the share.
CloudFileDirectory rootDir = share.getRootDirectoryReference();

现在,你已经有了共享所在的根目录的引用,因此可以使用以下代码来上传文件。Now that you have a reference to the root directory of the share, you can upload a file onto it using the following code.

        // Define the path to a local file.
        final String filePath = "C:\\temp\\Readme.txt";
    
        CloudFile cloudFile = rootDir.getFileReference("Readme.txt");
        cloudFile.uploadFromFile(filePath);

下载文件Download a file

对于 Azure 文件,需要更频繁执行的一项操作是下载文件。One of the more frequent operations you will perform against Azure Files is to download files. 在下面的示例中,代码会下载 SampleFile.txt 并显示其内容。In the following example, the code downloads SampleFile.txt and displays its contents.

//Get a reference to the root directory for the share.
CloudFileDirectory rootDir = share.getRootDirectoryReference();

//Get a reference to the directory that contains the file
CloudFileDirectory sampleDir = rootDir.getDirectoryReference("sampledir");

//Get a reference to the file you want to download
CloudFile file = sampleDir.getFileReference("SampleFile.txt");

//Write the contents of the file to the console.
System.out.println(file.downloadText());

删除文件Delete a file

另一项常见的 Azure 文件操作是删除文件。Another common Azure Files operation is file deletion. 下面的代码会删除名为 SampleFile.txt 的文件,该文件存储在名为 sampledir 的目录中。The following code deletes a file named SampleFile.txt stored inside a directory named sampledir.

// Get a reference to the root directory for the share.
CloudFileDirectory rootDir = share.getRootDirectoryReference();

// Get a reference to the directory where the file to be deleted is in
CloudFileDirectory containerDir = rootDir.getDirectoryReference("sampledir");

String filename = "SampleFile.txt"
CloudFile file;

file = containerDir.getFileReference(filename)
if ( file.deleteIfExists() ) {
    System.out.println(filename + " was deleted");
}

后续步骤Next steps

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