共用方式為

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

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

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

适用于

管理模型 计费模式 媒体层 冗余 SMB NFS
Microsoft.Storage 预配 v2 HDD(标准) 本地 (LRS) 是的 否
Microsoft.Storage 预配 v2 HDD(标准) 区域 (ZRS) 是的 否
Microsoft.Storage 预配 v2 HDD(标准) 异地 (GRS) 是的 否
Microsoft.Storage 预配 v2 HDD(标准) GeoZone (GZRS) 是的 否
Microsoft.Storage 预配版本 v1 SSD(高级) 本地 (LRS) 是的 否
Microsoft.Storage 预配版本 v1 SSD(高级) 区域 (ZRS) 是的 否
Microsoft.Storage 即用即付 HDD(标准) 本地 (LRS) 是的 否
Microsoft.Storage 即用即付 HDD(标准) 区域 (ZRS) 是的 否
Microsoft.Storage 即用即付 HDD(标准) 异地 (GRS) 是的 否
Microsoft.Storage 即用即付 HDD(标准) GeoZone (GZRS) 是的 否

关于使用 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)也可与 Azure SDK for Java 一起使用。

使用 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-identity 依赖项。 请注意,资源管理器项目不包括在 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 指令。 在此示例中,在 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 和文件共享客户端库:

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

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

本部分介绍如何使用适用于 Java 的文件共享客户端库来处理 Azure 文件资源。

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

授予访问权限并创建客户端

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

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

若要使用本文中的代码示例,请将 Azure RBAC 内置角色 存储文件数据特权参与者 分配给安全主体。 此角色对所有已配置存储帐户的共享中的所有数据具有完全读取、写入、修改 ACL、删除访问权限,而不考虑设置的文件/目录级别 NTFS 权限。 有关详细信息,请参阅 通过 REST 通过 Azure 文件 OAuth 使用 Microsoft Entra ID 访问 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.chinacloudapi.cn", accountName))
    .shareName(shareName)
    .credential(defaultAzureCredential)
    .buildClient();

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

如果确切地知道用于对用户进行身份验证的凭据类型,可以使用 适用于 Java 的 Azure 标识客户端库中的其他类获取 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.chinacloudapi.cn", accountName))
    .shareName(srcShareName)
    .shareTokenIntent(ShareTokenIntent.BACKUP)
    .resourcePath(srcFilePath)
    .credential(defaultAzureCredential)
    .buildFileClient();

ShareFileClient destShareFileClient = new ShareFileClientBuilder()
    .endpoint(String.format("https://%s.file.core.chinacloudapi.cn", 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.chinacloudapi.cn", 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 Key Vault 中安全地存储帐户密钥,请参阅 关于 Azure Key Vault 托管存储帐户密钥

使用 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_CHINA);

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_CHINA);

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 文件进行开发的详细信息,请参阅以下资源: