使用 Java 開發 Azure 檔案服務

了解開發使用 Azure 檔案儲存體來儲存資料的 Java 應用程式基本概念。 建立主控台應用程式,並了解使用 Azure 檔案儲存體 API 的基本動作:

  • 建立及刪除 Azure 檔案共用
  • 建立及刪除目錄
  • 列舉 Azure 檔案共用的檔案和目錄
  • 上傳、下載及刪除檔案

提示

請查看 Azure 儲存體程式碼範例儲存機制

如需可供您下載和執行的簡易端對端 Azure 儲存體程式碼範例,請查看我們的 Azure 儲存體範例清單。

適用於

檔案共用類型 SMB NFS
標準檔案共用 (GPv2)、LRS/ZRS Yes No
標準檔案共用 (GPv2)、GRS/GZRS Yes No
進階檔案共用 (FileStorage)、LRS/ZRS Yes No

建立 Java 應用程式

若要建置範例,您需要 Java Development Kit (JDK) 和適用於 Java 的 Azure 儲存體 SDK。 您也應該建立 Azure 儲存體帳戶。

設定您的應用程式以使用 Azure 檔案服務

若要使用 Azure 檔案儲存體 API,請將下列程式碼新增至您想要從中存取 Azure 檔案儲存體的 Java 檔案頂端。

// Include the following imports to use Azure Files APIs
import com.azure.storage.file.share.*;

設定 Azure 儲存體連接字串

若要使用 Azure 檔案服務,您必須連接到您的 Azure 儲存體帳戶。 設定連接字串,並且用來連線到您的儲存體帳戶。 定義靜態變數來保存連接字串。

<storage_account_name><storage_account_key> 取代為您的儲存體帳戶的實際值。

// 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>";

存取 Azure 檔案共用

若要存取 Azure 檔案儲存體,請建立 ShareClient 物件。 使用 ShareClientBuilder 類別來建置新的 ShareClient 物件。

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

建立檔案共用

Azure 檔案儲存體中的所有檔案和目錄都位於名為 [共用] 的容器中。

如果共用已存在,則 ShareClient.create 方法會擲回例外狀況。 在 try/catch 區塊中放置要建立的呼叫,並且處理例外狀況。

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;
    }
}

刪除檔案共用

下列範例程式碼會刪除檔案共用。

藉由呼叫 ShareClient.delete 方法來刪除共用。

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;
    }
}

建立目錄

藉由將檔案放在子目錄中,而不是將所有檔案都放在根目錄中,來組織儲存體。

下列程式碼會藉由呼叫 ShareDirectoryClient.create 來建立目錄。 範例方法會傳回 Boolean 值,指出是否成功建立目錄。

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;
    }
}

刪除目錄

刪除目錄是一項簡單的工作。 您無法刪除仍然包含檔案或子目錄的目錄。

如果目錄不存在或不是空的,則 ShareDirectoryClient.delete 方法會擲回例外狀況。 在 try/catch 區塊中放置要刪除的呼叫,並且處理例外狀況。

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 檔案共用的檔案和目錄

藉由呼叫 ShareDirectoryClient.listFilesAndDirectories 來取得檔案和目錄的清單。 方法會傳回您可以逐一查看的 ShareFileItem 物件清單。 下列程式碼會列出 dirName 參數所指定目錄內的檔案和目錄。

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;
    }
}

上傳檔案

了解如何從本機儲存體上傳檔案。

下列程式碼會藉由呼叫 ShareFileClient.uploadFromFile 方法,將本機檔案上傳至 Azure 檔案儲存體。 下列範例方法會傳回 Boolean 值,指出是否已成功上傳指定的檔案。

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;
    }
}

下載檔案

其中一個較頻繁的作業是從 Azure 檔案共用下載檔案。

下列範例會將指定檔案下載到 destDir 參數中指定的本機目錄。 範例方法會在前面加上日期和時間,讓下載的檔案名稱成為唯一的。

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;
    }
}

刪除檔案

另一個常見的 Azure 檔案服務作業是刪除檔案。

下列程式碼會刪除指定的指定檔案。 首先,範例會根據 dirName 參數建立 ShareDirectoryClient。 然後,程式碼會根據 fileName 參數,從目錄用戶端取得 ShareFileClient。 最後,範例方法會呼叫 ShareFileClient.delete 來刪除檔案。

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;
    }
}

下一步

如果您想要深入了解其他 Azure 儲存體 API,請參考下列連結。

如需使用已取代 JAVA 第 8 版 SDK 的相關程式碼範例,請參閱使用 JAVA 第 8 版的程式碼範例