通过


你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

使用 Java 针对 Azure 文件进行开发

了解如何开发使用Azure 文件存储存储数据的Java应用程序。 Azure 文件存储是云中的托管文件共享服务。 它提供可通过行业标准服务器消息块(SMB)和网络文件系统(NFS)协议访问的完全托管文件共享。 Azure 文件存储还提供 REST API,用于以编程方式访问文件共享。

在本文中,你将了解在Java中使用Azure 文件存储进行开发的不同方法,以及如何选择最符合应用需求的方法。 你还将了解如何创建与Azure 文件存储资源交互的基本控制台应用。

关于使用 Azure 文件存储实现 Java应用开发

Azure 文件存储为Java开发人员提供了多种方式来访问数据和管理Azure 文件存储中的资源。 下表列出了这些方法,总结了它们的工作方式,并提供有关何时使用每个方法的指导:

方法 工作原理 何时使用
标准文件 I/O 库 通过使用 SMB 或 NFS 装载的 Azure 文件共享使用 OS 级 API 调用。 使用 SMB/NFS 装载文件共享时,可以将文件 I/O 库用于编程语言或框架,例如 Java 的 java.iojava.nio 现有的业务应用使用标准文件 I/O,你不希望重写代码来使应用兼容 Azure 文件共享。
FileREST API 直接调用 HTTPS 终结点以与存储在Azure 文件存储中的数据进行交互。 提供对文件共享资源的编程控制。 Azure SDK提供基于 FileREST API 的文件共享客户端库(com.azure.storage.file.share),允许你通过熟悉 Java的编程语言范例与 FileREST API 操作进行交互。 你要为客户生成增值云服务和应用,并且想要使用无法通过标准文件 I/O 库提供的高级功能。
存储资源提供程序 REST API 使用 Azure 资源管理器 (ARM) 来管理存储帐户和文件共享。 为了进行各种资源管理操作,调用REST API终结点。 应用或服务需要执行资源管理任务,例如创建、删除或更新存储帐户或文件共享。

有关这些方法的一般信息,请参阅Azure 文件存储 应用程序开发概述

本文重点介绍如何使用以下方法处理Azure 文件存储资源:

先决条件

配置你的环境

注释

本文使用 Maven 生成工具生成并运行示例代码。 其他生成工具(如 Gradle)也适用于Java Azure SDK。

使用 Maven 创建新的控制台应用,或打开现有项目。 按照以下步骤安装包并添加必要的 import 指令。

安装软件包

在文本编辑器中打开 pom.xml 文件。 通过包括 BOM 文件包括直接依赖项来安装包。

包括 BOM 文件

添加 azure-sdk-bom 以依赖最新版本的库。 在以下代码片段中,将 {bom_version_to_target} 占位符替换为版本号。 使用 azure-sdk-bom 使你不必指定每个依赖项的版本。 若要了解有关 BOM 的详细信息,请参阅 Azure SDK BOM 自述文件

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.azure</groupId>
            <artifactId>azure-sdk-bom</artifactId>
            <version>{bom_version_to_target}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

将以下依赖项元素添加到依赖项组。 azure标识依赖项是与 Azure 服务的无密码连接所必需的。 请注意,资源管理器项目不包括在 BOM 文件中,因此需要将它们添加为直接依赖项。

<dependency>
  <groupId>com.azure</groupId>
  <artifactId>azure-storage-file-share</artifactId>
</dependency>
<dependency>
  <groupId>com.azure</groupId>
  <artifactId>azure-identity</artifactId>
</dependency>
<dependency>
  <groupId>com.azure</groupId>
  <artifactId>azure-core-management</artifactId>
</dependency>
<dependency>
  <groupId>com.azure.resourcemanager</groupId>
  <artifactId>azure-resourcemanager</artifactId>
  <version>{package_version_to_target}</version>
</dependency>
<dependency>
  <groupId>com.azure.resourcemanager</groupId>
  <artifactId>azure-resourcemanager-storage</artifactId>
  <version>{package_version_to_target}</version>
</dependency>

包括一个直接依赖项

若要依赖特定版本的库,请将直接依赖项添加到项目:

<dependency>
  <groupId>com.azure</groupId>
  <artifactId>azure-storage-file-share</artifactId>
  <version>{package_version_to_target}</version>
</dependency>
<dependency>
  <groupId>com.azure</groupId>
  <artifactId>azure-identity</artifactId>
  <version>{package_version_to_target}</version>
</dependency>
<dependency>
  <groupId>com.azure.resourcemanager</groupId>
  <artifactId>azure-resourcemanager</artifactId>
  <version>{package_version_to_target}</version>
</dependency>
<dependency>
  <groupId>com.azure.resourcemanager</groupId>
  <artifactId>azure-resourcemanager-storage</artifactId>
  <version>{package_version_to_target}</version>
</dependency>
<dependency>
  <groupId>com.azure</groupId>
  <artifactId>azure-core-management</artifactId>
  <version>{package_version_to_target}</version>
</dependency>

包括 import 指令

然后打开代码文件并添加必要的 import 指令。 在此示例中,我们在 App.java 文件中添加以下指令:

import com.azure.identity.*;
import com.azure.storage.file.share.*;
import com.azure.resourcemanager.*;
import com.azure.resourcemanager.storage.models.*;
import com.azure.core.management.*;
import com.azure.core.management.profile.*;

如果计划使用Java文件 I/O 库,则还需要添加以下导入指令:

import java.io.*;
import java.nio.file.*;

使用 Java 文件 I/O 库来处理 Azure 文件存储

标准文件 I/O 库是访问和使用Azure 文件存储资源的最常用方法。 使用 SMB 或 NFS 装载文件共享时,操作系统会重定向本地文件系统的 API 请求。 此方法允许你使用标准文件 I/O 库(例如 java.io ,以及 java.nio)与共享中的文件和目录进行交互。

在应用需要时,请考虑使用Java文件 I/O 库:

  • 应用兼容性:非常适合已有代码且已使用 Java 文件 I/O 库的业务线应用。 无需为应用重写代码,才能使用Azure文件共享。
  • 易用: Java文件 I/O 库是开发人员熟知的,易于使用。 Azure 文件存储的关键价值主张是通过 SMB 和 NFS 公开本机文件系统 API。

本部分介绍如何使用Java文件 I/O 库来处理Azure 文件存储资源。

有关详细信息和示例,请参阅以下资源:

挂载文件共享

若要使用Java文件 I/O 库,必须先装载文件共享。 有关如何使用 SMB 或 NFS 装载文件共享的指导,请参阅以下资源:

在本文中,我们将使用以下路径来引用装载在 Windows 上的 SMB 文件共享:

String fileSharePath = "Z:\\file-share";

示例:使用Java文件 I/O 库连接到文件共享并枚举目录

下面的代码示例演示如何连接到文件共享并列出共享中的目录:

import java.io.*;
import java.nio.file.*;

// Add the following code to a new or existing function

String fileSharePath = "Z:\\file-share";

try {
    File directory = new File(fileSharePath);
    File[] dirs = directory.listFiles(File::isDirectory);
            
    if (dirs != null) {
        for (File dir : dirs) {
            System.out.println(dir.getName());
        }
        System.out.println(dirs.length + " directories found.");
    }
} catch (Exception e) {
    System.out.println("Error: " + e.getMessage());
}

示例:使用Java文件 I/O 库写入文件共享中的文件

下面的代码示例演示如何将文本写入文件并将其追加到文件中:

import java.io.*;
import java.nio.file.*;
import java.util.Arrays;

// Add the following code to a new or existing function

String fileSharePath = "Z:\\file-share";
String fileName = "test.txt";

try {
    String textToWrite = "First line" + System.lineSeparator();
    Path filePath = Paths.get(fileSharePath, fileName);
        
    // Write initial content to file
    Files.write(filePath, textToWrite.getBytes());
    System.out.println("Initial text written to file");
        
    // Append additional lines to the file
    String[] textToAppend = { "Second line", "Third line" };
    Files.write(filePath, 
                Arrays.asList(textToAppend),
                StandardOpenOption.APPEND);
    System.out.println("Additional lines appended to file");
} catch (IOException ex) {
    System.out.println("Error writing to file: " + ex.getMessage());
}

示例:使用Java文件 I/O 库锁定文件共享中的文件

装载文件共享的 SMB 客户端可以使用文件系统锁定机制来管理对共享文件的访问。

以下代码示例演示如何锁定文件共享中的文件:

import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.file.*;

// Add the following code to a new or existing function

String fileSharePath = "Z:\\file-share";
String fileName = "test.txt";
String filePath = Paths.get(fileSharePath, fileName).toString();

try (
    FileOutputStream fos = new FileOutputStream(filePath);
    FileChannel fileChannel = fos.getChannel()) {

    // Acquire an exclusive lock on this file
    FileLock lock = fileChannel.lock();

    System.out.println("File is locked.");

    // Perform file operations here

    // Release the lock
    lock.release();
    System.out.println("File lock released.");

} catch (Exception e) {
    e.printStackTrace();
}

同时使用 SMB 和 FileREST API 时,请记住,FileREST API 使用 租约 来管理文件锁,而 SMB 使用由作系统管理的文件系统锁。 若要详细了解如何管理 SMB 与 FileREST API 之间的文件锁定交互,请参阅 管理文件锁

示例:使用Java文件 I/O 库枚举文件 ACL

下面的代码示例演示如何枚举文件的访问控制列表(ACL):

import java.nio.file.*;
import java.nio.file.attribute.AclEntry;
import java.nio.file.attribute.AclFileAttributeView;
import java.util.List;

// Add the following code to a new or existing function

String fileSharePath = "Z:\\file-share";
String fileName = "test.txt";
String filePath = Paths.get(fileSharePath, fileName).toString();

try {
    Path path = Paths.get(filePath);

    // Get the ACL view for the file
    AclFileAttributeView aclView = Files.getFileAttributeView(
            path, AclFileAttributeView.class);

    // Get the ACL entries
    List<AclEntry> aclEntries = aclView.getAcl();

    // List all access rules for the file
    for (AclEntry entry : aclEntries) {
        System.out.println("Identity: " + entry.principal().getName());
        System.out.println("Access Control Type: " + entry.type());
        System.out.println("File System Rights: " + entry.permissions());
        System.out.println();
    }

    System.out.println(aclEntries.size() + " ACL entries found.");
} catch (Exception ex) {
    System.out.println("Error: " + ex.getMessage());
}

使用适用于 Java 的文件共享客户端库处理 Azure 文件

FileREST API 提供对Azure 文件存储的编程访问。 它允许调用 HTTPS 端点来对文件共享、目录和文件执行操作。 FileREST API 旨在实现高可伸缩性和高级功能,这些功能可能无法通过本机协议使用。 Azure SDK提供基于 FileREST API 生成的客户端库(例如用于 Java 的文件共享客户端库)。

如果应用程序需要,请考虑使用 FileREST API 和文件共享客户端库:

  • 高级功能: 访问无法通过原生协议获得的操作和功能。
  • Custom 云集成:生成直接与Azure 文件存储交互的自定义增值服务,例如备份、防病毒或数据管理。
  • 性能优化: 在大规模场景中,通过数据平面操作享受性能优势。

FileREST API 将 Azure 文件存储 表示为资源的层次结构,建议用于在 directoryfile 级别执行的操作。 对于在文件服务文件共享级别执行的作,应首选存储资源提供程序 REST API

在本部分中,你将了解如何使用适用于 Java 的文件共享客户端库来处理 Azure 文件资源。

有关详细信息和示例,请参阅以下资源:

授权访问并创建客户端

若要将应用连接到Azure 文件存储,请创建一个 ShareClient 对象。 此对象是处理Azure 文件存储资源的起点。 以下代码示例演示如何使用不同的授权机制创建 ShareClient 对象。

若要使用Microsoft Entra ID进行授权,您需要使用一个安全主体。 需要哪种类型的安全主体取决于应用运行的位置。 若要了解有关身份验证方案的详细信息,请参阅Azure使用Java和Azure标识进行身份验证

若要使用本文中的代码示例,请将 Azure RBAC 内置角色Storage 文件数据特权参与者分配给安全主体。 此角色对所有已配置存储帐户的共享中的所有数据具有完全读取、写入、修改 ACL、删除访问权限,而不考虑设置的文件/目录级别 NTFS 权限。 有关详细信息,请参阅 使用 Microsoft Entra ID 通过 REST 上的 OAuth 访问 Azure 文件共享

使用 DefaultAzureCredential 授权访问

授权访问和连接到 Azure 文件存储的一种简单且安全的方法是通过创建 DefaultAzureCredential 实例来获取 OAuth 令牌。 然后,可以使用该凭据创建对象 ShareClient

以下示例创建一个 ShareClient 使用 DefaultAzureCredential授权的对象,然后创建一个 ShareDirectoryClient 对象来处理共享中的目录:

import com.azure.core.credential.TokenCredential;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.storage.file.share.*;

// Add the following code to a new or existing function

String accountName = "<account-name>";
String shareName = "<share-name>";
TokenCredential defaultAzureCredential = new DefaultAzureCredentialBuilder().build();

// Create the ShareClient
ShareClient shareClient = new ShareClientBuilder()
    .endpoint(String.format("https://%s.file.core.windows.net", accountName))
    .shareName(shareName)
    .credential(defaultAzureCredential)
    .buildClient();

// Create a client to interact with a directory in the share
ShareDirectoryClient directoryClient = shareClient.getDirectoryClient("sample-directory");

如果确切知道用于对用户进行身份验证的凭据类型,则可以使用 Azure 身份验证客户端库 Java 中的其他类获取 OAuth 令牌。 这些类派生自 TokenCredential 类。

若要详细了解每种授权机制,请参阅 “选择如何授权访问文件数据”。

示例:使用文件共享客户端库复制文件

可以使用以下方法在文件共享内或文件共享之间复制文件:

您可以使用 BlockBlobClient 对象中的以下方法将文件复制到目标 Blob。

下面的代码示例演示如何将文件复制到另一个文件共享中的文件:

import java.time.*;
import java.util.*;

import com.azure.core.credential.TokenCredential;
import com.azure.core.util.polling.*;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.storage.file.share.*;
import com.azure.storage.file.share.models.*;

// Add the following code to a new or existing function

String accountName = "<account-name>";
String srcShareName = "src-file-share";
String destShareName = "dest-file-share";
String srcFilePath = "src/path/to/file";
String destFilePath = "dest/path/to/file";

TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build();

ShareFileClient srcShareFileClient = new ShareFileClientBuilder()
    .endpoint(String.format("https://%s.file.core.windows.net", accountName))
    .shareName(srcShareName)
    .shareTokenIntent(ShareTokenIntent.BACKUP)
    .resourcePath(srcFilePath)
    .credential(defaultAzureCredential)
    .buildFileClient();

ShareFileClient destShareFileClient = new ShareFileClientBuilder()
    .endpoint(String.format("https://%s.file.core.windows.net", accountName))
    .shareName(destShareName)
    .shareTokenIntent(ShareTokenIntent.BACKUP)
    .resourcePath(destFilePath)
    .credential(defaultAzureCredential)
    .buildFileClient();

// Copy the file from the source share to the destination share
SyncPoller<ShareFileCopyInfo, Void> poller = destShareFileClient
        .beginCopy(srcShareFileClient.getFileUrl(),
                Collections.singletonMap("file", "metadata"),
                Duration.ofSeconds(2));

final PollResponse<ShareFileCopyInfo> pollResponse = poller.poll();
final ShareFileCopyInfo value = pollResponse.getValue();
System.out.printf("Copy source: %s. Status: %s.%n", value.getCopySourceUrl(), value.getCopyStatus());

示例:使用文件共享客户端库租用文件

租约通过租约 ID 对由Azure管理的文件创建锁。 租约提供了一种机制,用于协调对分布式系统中多个客户端的文件的访问。 文件的租约提供独占写入和删除访问权限。 若要详细了解租约状态和作,请参阅 租约文件

下面的代码示例演示如何创建租约客户端、获取文件的无限持续时间租约以及释放租约:

import com.azure.core.credential.TokenCredential;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.storage.file.share.*;
import com.azure.storage.file.share.models.*;
import com.azure.storage.file.share.specialized.*;

// Add the following code to a new or existing function

String accountName = "<account-name>";
String shareName = "sample-file-share";
String filePath = "path/to/file";
        
TokenCredential defaultAzureCredential = new DefaultAzureCredentialBuilder().build();

ShareFileClient fileClient = new ShareFileClientBuilder()
    .endpoint(String.format("https://%s.file.core.windows.net", accountName))
    .shareName(shareName)
    .shareTokenIntent(ShareTokenIntent.BACKUP)
    .resourcePath(filePath)
    .credential(defaultAzureCredential)
    .buildFileClient();

// Get a ShareLeaseClient
ShareLeaseClient fileLeaseClient = new ShareLeaseClientBuilder()
        .fileClient(fileClient)
        .shareTokenIntent(ShareTokenIntent.BACKUP)
        .buildClient();
        
try {
    // Acquire a lease on the file with infinite duration
    fileLeaseClient.acquireLease();
    System.out.println("Lease acquired successfully");
            
    // Do something with the file

} catch (Exception e) {
    System.err.println("Error: " + e.getMessage());
} finally {
    // Release the lease when finished
    try {
        fileLeaseClient.releaseLease();
        System.out.println("Lease released successfully.");
    } catch (Exception e) {
        System.err.println(e.getMessage());
    }
}

同时使用 SMB 和 FileREST API 时,请记住,FileREST API 使用 租约 来管理文件锁,而 SMB 使用由作系统管理的文件系统锁。 若要详细了解如何管理 SMB 与 FileREST API 之间的文件锁定交互,请参阅 管理文件锁

示例:使用文件共享客户端库创建和列出共享快照

共享快照是某个时间点文件共享的只读副本。 可以创建文件共享的快照,然后在创建快照时使用快照访问共享中的数据。 还可以列出文件共享中的所有快照,并删除共享快照。

以下代码示例演示如何创建共享快照、列出文件共享中的快照,以及遍历共享快照中的目录树:

import com.azure.storage.file.share.*;
import com.azure.storage.file.share.models.*;

// Add the following code to a new or existing function

public static void main(String[] args) {
    String connectionString = "<connection-string>";

    // Create a ShareServiceClient from which you can create clients for specific shares
    ShareServiceClient shareServiceClient = new ShareServiceClientBuilder()
    .connectionString(connectionString)
        .buildClient();
        
    // Get a client for a specific share
    ShareClient shareClient = shareServiceClient.getShareClient("sample-file-share");

    try {
        // Create a snapshot
        ShareSnapshotInfo snapshotInfo = shareClient.createSnapshot();
        System.out.println("Snapshot created: " + snapshotInfo.getSnapshot());

        // List snapshots in a share
        ListSharesOptions options = new ListSharesOptions()
            .setIncludeSnapshots(true);
                
        for (ShareItem shareItem : shareServiceClient.listShares(options, null, null)) {
            if (shareItem.getSnapshot() != null) {
                System.out.println("Share: " + shareItem.getName() + 
                    " (Snapshot: " + shareItem.getSnapshot() + ")");
            }
        }

        // List directories and files in a share snapshot
        String snapshotTimestamp = snapshotInfo.getSnapshot();
        ShareClient shareSnapshot = shareClient.getSnapshotClient(snapshotTimestamp);
        ShareDirectoryClient rootDir = shareSnapshot.getRootDirectoryClient();

        listDirectoryTree(rootDir);
            
    } catch (Exception e) {
        System.err.println("Error: " + e.getMessage());
    }
 }
    
private static void listDirectoryTree(ShareDirectoryClient directory) {
    // List all files and directories in current directory
    for (ShareFileItem fileItem : directory.listFilesAndDirectories()) {
        if (fileItem.isDirectory()) {
            System.out.println("Directory: " + fileItem.getName());
            // Recursively list subdirectory contents
            listDirectoryTree(directory.getSubdirectoryClient(fileItem.getName()));
        } else {
            System.out.println("File: " + fileItem.getName());
        }
    }
}

注释

文件共享级别的数据平面操作不允许使用 OAuth 令牌,例如使用 DefaultAzureCredential 时获取的令牌。 若要使用共享快照,必须使用帐户密钥对客户端对象进行授权。 在此代码示例中创建的 ShareClient 对象使用连接字符串,其中包括帐户密钥。

存储帐户密钥或连接字符串会带来安全风险。 仅当Microsoft Entra身份验证不可用时,才应使用它们。 若要详细了解如何安全地授权访问存储,请参阅 授权访问 Azure 存储中的数据

使用Azure 存储管理库管理Azure 文件存储资源

Azure 存储管理库基于Azure 存储资源提供程序 REST API 构建。 Azure 存储资源提供程序是基于 Azure 资源管理器 的服务,支持声明性(模板)和命令性(直接 API 调用)方法。 Azure 存储资源提供程序 REST API 提供对Azure 存储资源的编程访问,包括文件共享。 Azure SDK提供基于Azure 存储资源提供程序 REST API 构建的管理库。

对于在 文件服务文件共享 级别执行的作,建议使用管理库。 本部分介绍如何使用Azure 存储管理库来管理Azure 文件存储资源。

Azure 存储管理库基于Azure 存储资源提供程序 REST API 构建。 Azure 存储资源提供程序是基于 Azure 资源管理器 的服务,支持声明性(模板)和命令性(直接 API 调用)方法。 Azure 存储资源提供程序 REST API 提供对Azure 存储资源的编程访问,包括文件共享。 Azure SDK提供基于Azure 存储资源提供程序 REST API 构建的管理库。

对于在 文件服务文件共享 级别执行的作,建议使用管理库。 本部分介绍如何使用Azure 存储管理库来管理Azure 文件存储资源。

示例:使用Azure 存储管理库创建文件共享

下面的代码示例演示如何创建顶级 AzureResourceManager 对象、向订阅注册存储资源提供程序,以及使用Azure 存储管理库创建文件共享:

import com.azure.identity.*;
import com.azure.resourcemanager.*;
import com.azure.resourcemanager.storage.fluent.*;
import com.azure.resourcemanager.storage.fluent.models.*;

import com.azure.core.credential.TokenCredential;
import com.azure.core.management.*;
import com.azure.core.management.profile.*;

// Add the following code to a new or existing function

String subscriptionID = "<subscription-id>";
String rgName = "<resource-group-name>";
String saName = "<storage-account-name>";
TokenCredential credential = new DefaultAzureCredentialBuilder().build();
AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE);

AzureResourceManager armClient = AzureResourceManager
        .configure()
        .authenticate(credential, profile)
        .withSubscription(subscriptionID);

// Check the registration state of the resource provider and register, if needed
if (armClient.providers().getByName("Microsoft.Storage").registrationState() == "NotRegistered")
    armClient.providers().register("Microsoft.Storage");

// Create a new file share

StorageManagementClient storageManagementClient = armClient.storageAccounts().manager().serviceClient();
FileSharesClient fileShare = storageManagementClient.getFileShares();

String shareName = "sample-file-share";
int quotaInGB = 1;
        
// Create the file share
fileShare.create(
    rgName,
    saName,
    shareName,
    new FileShareInner()
        .withShareQuota(quotaInGB)
);

可以使用 FileShareInner 类配置文件共享属性。 前面的示例演示如何在创建文件共享时设置共享配额。 若要更新现有文件共享,请调用 fileShare.update() 并传入包含所需更新属性的 FileShareInner 对象。

注释

若要执行注册操作,您需要具有以下 Azure RBAC 操作的权限:Microsoft.Storage/register/action。 此权限包含在参与者和所有者内置角色中。

示例:使用Azure 存储管理库列出文件共享和快照

以下代码示例演示如何列出存储帐户中的文件共享和快照:

import com.azure.identity.*;
import com.azure.resourcemanager.*;
import com.azure.resourcemanager.storage.fluent.*;
import com.azure.resourcemanager.storage.fluent.models.*;

import com.azure.core.credential.TokenCredential;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.management.*;
import com.azure.core.management.profile.*;
import com.azure.core.util.Context;

// Add the following code to a new or existing function

String subscriptionID = "<subscription-id>";
String rgName = "<resource-group-name>";
String saName = "<storage-account-name>";
TokenCredential credential = new DefaultAzureCredentialBuilder().build();
AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE);

AzureResourceManager armClient = AzureResourceManager
        .configure()
        .authenticate(credential, profile)
        .withSubscription(subscriptionID);

// Check the registration state of the resource provider and register, if needed
if (armClient.providers().getByName("Microsoft.Storage").registrationState() == "NotRegistered")
    armClient.providers().register("Microsoft.Storage");

StorageManagementClient storageManagementClient = armClient.storageAccounts().manager().serviceClient();
FileSharesClient fileShare = storageManagementClient.getFileShares();

// List all file shares and include snapshots

PagedIterable<FileShareItemInner> fileShares = fileShare.list(
    rgName,               // resource group name
    saName,               // storage account name
    null,                 // maxpagesize
    null,                 // filter
    "snapshots",          // expand to include snapshots
    Context.NONE);        // context

for (FileShareItemInner fileShareItem : fileShares) {
    System.out.println("File share name: " + fileShareItem.name());
    System.out.println("File share quota: " + fileShareItem.shareQuota());
}

后续步骤

有关使用 Azure 文件存储 进行开发的详细信息,请参阅以下资源: