Java での Azure Files 用の開発

データを格納するために Azure Files を使用する Java アプリケーションの開発の基本について説明します。 コンソール アプリケーションを作成し、Azure Files API を使用して基本的な操作を学習します。

  • Azure ファイル共有を作成および削除する
  • ディレクトリを作成および削除する
  • Azure ファイル共有のファイルとディレクトリを列挙する
  • ファイルのアップロード、ダウンロード、および削除

ヒント

Azure Storage コード サンプル レポジトリを参照してください

ダウンロードして実行できる、使いやすいエンド ツー エンドの Azure Storage コード サンプルについては、Azure Storage のサンプルの一覧を確認してください。

適用対象

ファイル共有の種類 SMB NFS
Standard ファイル共有 (GPv2)、LRS/ZRS はい いいえ
Standard ファイル共有 (GPv2)、GRS/GZRS はい いいえ
Premium ファイル共有 (FileStorage)、LRS/ZRS はい いいえ

Java アプリケーションの作成

サンプルを作成するには、Java Development Kit (JDK) と Azure Storage SDK for Java が必要です。 また、Azure ストレージ アカウントを作成しておく必要があります。

Azure Files を使用するようにアプリケーションを設定する

Azure Files API を使用するには、Azure Files のアクセス元にする Java ファイルの一番上に次のコードを追加します。

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

Azure Storage 接続文字列の設定

Azure Files を使うには、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 Files にアクセスするため、ShareClient オブジェクトを作成します。 ShareClientBuilder クラスを使用して、新しい ShareClient オブジェクトを作成します。

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

ファイル共有を作成する

Azure Files のすべてのファイルとディレクトリは共有という名前のコンテナーにあります。

共有が既に存在する場合は、ShareClient.create メソッドによって例外がスローされます。 try/catch ブロックの create に呼び出しを配置して例外を処理します。

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 ブロックの delete に呼び出しを配置して例外を処理します。

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 Files にアップロードします。 次のメソッド例は、指定したファイルが正常にアップロードされたかどうかを示す 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;
    }
}

ファイルをダウンロードする

頻繁に実行する操作の 1 つに、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 Files でのもう 1 つの一般的な操作はファイルの削除です。

次のコードは、指定したファイルを削除します。 この例はまず、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 を使用したコード サンプル」を参照してください。