使用 Java 開發 Azure 檔案儲存服務

✔️ 適用於: 使用 Microsoft.Storage 資源提供者建立的經典 SMB 和 NFS 檔案共享。

✖️ 不適用於:使用 Microsoft.FileShares 資源提供者建立的檔案共用

學習如何開發使用 Azure 檔案儲存體 來儲存資料的 Java 應用程式。 Azure 檔案儲存體 是一個雲端管理式檔案分享服務。 它提供完全託管的檔案共用,可透過業界標準伺服器訊息區塊 (SMB) 和網路檔案系統 (NFS) 協定存取。 Azure 檔案儲存體 也提供一個 REST API,方便程式化存取檔案分享。

在本文中,您將了解使用 Azure 檔案儲存體 在 Java 中開發的不同方法,以及如何選擇最適合您應用程式需求的方法。 你也會學習如何建立一個基本的主控台應用程式,能與 Azure 檔案儲存體 資源互動。

關於使用 Azure 檔案儲存體 進行 Java 應用程式開發

Azure 檔案儲存體 提供多種方式,讓 Java 開發者能存取資料並管理 Azure 檔案儲存體 中的資源。 下表列出這些方法、摘要說明其運作方式,並提供使用每個方法時機的指引:

方法 運作方式 使用時機
標準檔案輸入/輸出函式庫 透過使用 SMB 或 NFS 掛載的 Azure 檔案共用使用作業系統層級的 API 呼叫。 當你使用 SMB/NFS 掛載檔案分享時,可以使用程式語言或框架的檔案 I/O 函式庫,例如 java.io 和 java.nio 用於 Java。 你有業務線應用程式,已有使用標準檔案輸入輸出的程式碼,你不想為了讓應用程式能與 Azure 檔案分享相容而重寫程式碼。
檔案REST API 直接呼叫 HTTPS 端點來與儲存在 Azure 檔案儲存體 中的資料互動。 提供檔案共用資源的程序設計控制。 Azure SDK 提供了建立在 FileREST API 上的檔案分享用戶端函式庫com.azure.storage.file.share(),因此你可以透過熟悉的 Java 程式語言範式與 FileREST API 操作互動。 你正在為客戶打造增值的雲端服務和應用程式,並且想使用標準檔案 I/O 函式庫無法提供的進階功能。
記憶體資源提供者 REST API 使用 Azure Resource Manager(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 README。

<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-identity 依賴性是無密碼連接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 指令。 此範例在 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 函式庫:

  • App 相容性: 非常適合已有程式碼且已使用 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 的 File Shares 用戶端函式庫來操作 Azure 檔案儲存體

FileREST API 提供對 Azure 檔案儲存體的程式設計存取權。 它可讓您呼叫 HTTPS 端點,以在檔案共享、目錄和檔案上執行作業。 FileREST API 是針對可能無法透過原生通訊協定使用的高延展性和進階功能所設計。 Azure SDK 提供客戶端函式庫,例如 Java 的檔案共享用戶端函式庫,這些函式庫建構在 FileREST API 之上。

如果您的應用程式需要以下條件,請考慮使用 FileREST API 和 File Shares 用戶端函式庫:

  • 進階功能: 存取無法透過原生通訊協定使用的各項操作與功能。
  • 自訂雲端整合: 建立自訂增值服務,如備份、防毒或資料管理,直接與Azure 檔案儲存體互動。
  • 效能優化: 使用資料平面操作,在大規模情境中受益於效能優勢。

FileREST API 將 Azure 檔案儲存體 建模為資源階層。 用它來執行你在 目錄 或 檔案 層級執行的操作。 對於在 檔案服務 或 檔案分享 層級執行的操作,請使用 Storage resource provider REST API。

在本節中,您將學習如何使用 Java 的檔案分享用戶端函式庫來搭配 Azure 檔案儲存體 資源。

如需詳細資訊和範例,請參閱下列資源:

授權存取並建立用戶端

要將應用程式連接到 Azure 檔案儲存體,請建立一個 ShareClient 物件。 這個物件是你使用 Azure 檔案儲存體 資源的起點。 下列程式碼範例示範如何使用不同的授權機制來建立 ShareClient 物件。

若要使用 Microsoft Entra ID 授權,請使用安全性主體。 您需要的安全性主體類型取決於您的應用程式執行位置。 欲了解更多認證情境,請參閱 Azure 與 Java 及 Azure Identity。

要處理本文中的程式碼範例,請將 Azure RBAC 內建角色 Storage File Data Privileged Contributor 指派給安全主體。 此角色會針對所有已設定的儲存體帳戶,提供共用中所有資料的完整讀取、寫入、修改 ACL 和刪除存取權,而不論所設定的檔案/目錄層級 NTFS 權限為何。 欲了解更多資訊,請參閱 使用 Microsoft Entra ID 和 Azure 檔案儲存體 OAuth 透過 REST 存取 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 Identity 客戶端函式庫中的其他類別取得 OAuth 憑證,適用於 Java。 這些類別衍生自 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 Resource Manager 的服務,支援宣告式(範本)與命令式(直接 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 檔案儲存體 開發的資訊,請參閱以下資源: