すべてのプロダクト
Search
ドキュメントセンター

Object Storage Service:ディレクトリの管理 (Java SDK V1)

最終更新日:Nov 29, 2025

フラットな構造では管理が困難になる可能性がある多数のオブジェクトの編成と管理を簡素化するために、Object Storage Service (OSS) はフォルダ構造をシミュレートするディレクトリ機能を提供します。

注意事項

  • このトピックでは、中国 (杭州) リージョンのパブリックエンドポイントを使用します。 同じリージョン内の他の Alibaba Cloud サービスから OSS にアクセスするには、内部エンドポイントを使用します。 サポートされているリージョンとエンドポイントの詳細については、「リージョンとエンドポイント」をご参照ください。

  • このトピックでは、アクセス認証情報は環境変数から取得されます。 アクセス認証情報の設定方法の詳細については、「アクセス認証情報の設定」をご参照ください。

  • このトピックでは、OSS エンドポイントを使用して OSSClient インスタンスを作成します。 カスタムドメイン名または Security Token Service (STS) を使用して OSSClient インスタンスを作成する場合は、「一般的なシナリオの設定例」をご参照ください。

ディレクトリの作成

次のコードは、ディレクトリを作成する 2 つのメソッドを提供します。

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import java.io.ByteArrayInputStream;

public class Demo {

    public static void main(String[] args) throws Exception {
        // 中国 (杭州) リージョンを例として使用します。他のリージョンについては、必要に応じて値を変更してください。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 環境変数からアクセス認証情報を取得します。サンプルコードを実行する前に、OSS_ACCESS_KEY_ID および OSS_ACCESS_KEY_SECRET 環境変数が設定されていることを確認してください。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // バケット名を指定します。例:examplebucket。
        String bucketName = "examplebucket";
        // メソッド 1 を使用して作成するディレクトリの名前を指定します。
        String dirName = "exampledir/";
        // メソッド 2 を使用して作成するディレクトリの名前を指定します。
        String dirName2 = "exampledir1/";
        // バケットが配置されているリージョンを指定します。たとえば、バケットが中国 (杭州) リージョンにある場合は、Region を cn-hangzhou に設定します。
        String region = "cn-hangzhou";

        // OSSClient インスタンスを作成します。
        // OSSClient インスタンスが不要になったら、shutdown メソッドを呼び出してリソースを解放します。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // メソッド 1:createDirectory 操作を呼び出してディレクトリを直接作成します。このメソッドを使用してディレクトリを作成する前に、階層型名前空間を有効にする必要があります。
            ossClient.createDirectory(bucketName, dirName);

            // メソッド 2:空の文字列をアップロードしてディレクトリを作成します。
            ossClient.putObject(bucketName, dirName2, new ByteArrayInputStream("".getBytes()));
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

ディレクトリの名前変更

バケットの階層型名前空間機能を有効にすると、バケット内のディレクトリの名前を変更できます。

次のコードは、examplebucket バケット内の exampledir ディレクトリの名前を newexampledir に変更する方法の例を示しています。

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        // yourEndpoint を、バケットが配置されているリージョンのエンドポイントに設定します。たとえば、バケットが中国 (杭州) リージョンにある場合は、エンドポイントを https://oss-cn-hangzhou.aliyuncs.com に設定します。
        String endpoint = "yourEndpoint";
        // 環境変数からアクセス認証情報を取得します。サンプルコードを実行する前に、OSS_ACCESS_KEY_ID および OSS_ACCESS_KEY_SECRET 環境変数が設定されていることを確認してください。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // バケット名を指定します。例:examplebucket。
        String bucketName = "examplebucket";
        // ソースディレクトリの絶対パスを指定します。絶対パスにバケット名を含めることはできません。
        String sourceDir = "exampledir";
        // ソースディレクトリと同じバケット内の宛先ディレクトリの絶対パスを指定します。絶対パスにバケット名を含めることはできません。
        String destinationDir = "newexampledir";
        // バケットが配置されているリージョンを指定します。たとえば、バケットが中国 (杭州) リージョンにある場合は、Region を cn-hangzhou に設定します。
        String region = "cn-hangzhou";

        // OSSClient インスタンスを作成します。
        // OSSClient インスタンスが不要になったら、shutdown メソッドを呼び出してリソースを解放します。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // バケット内のソースディレクトリの名前を宛先ディレクトリに変更します。
            RenameObjectRequest renameObjectRequest = new RenameObjectRequest(bucketName, sourceDir, destinationDir);
            ossClient.renameObject(renameObjectRequest);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

ディレクトリの削除

警告

ディレクトリを削除すると、そのすべてのサブディレクトリとオブジェクトも削除されます。操作は慎重に行ってください。

バケット内の指定されたディレクトリは、非再帰的削除または再帰的削除を使用して削除できます。

非再帰的削除

非再帰的削除を使用する場合、空のディレクトリのみを削除できます。

次のコードは、examplebucket バケットから exampledir ディレクトリを非再帰的に削除する方法の例を示しています。

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;

public class Demo {
    public static void main(String[] args) throws Exception {
        // yourEndpoint を、バケットが配置されているリージョンのエンドポイントに設定します。たとえば、バケットが中国 (杭州) リージョンにある場合は、エンドポイントを https://oss-cn-hangzhou.aliyuncs.com に設定します。
        String endPoint = "yourEndpoint";
        // 環境変数からアクセス認証情報を取得します。サンプルコードを実行する前に、OSS_ACCESS_KEY_ID および OSS_ACCESS_KEY_SECRET 環境変数が設定されていることを確認してください。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // バケット名を指定します。
        String bucketName = "examplebucket";
        // ディレクトリの絶対パスを指定します。絶対パスにバケット名を含めることはできません。
        String directoryName = "exampledir";
        // バケットが配置されているリージョンを指定します。たとえば、バケットが中国 (杭州) リージョンにある場合は、Region を cn-hangzhou に設定します。
        String region = "cn-hangzhou";

        // OSSClient インスタンスを作成します。
        // OSSClient インスタンスが不要になったら、shutdown メソッドを呼び出してリソースを解放します。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // ディレクトリを削除します。デフォルトでは、非再帰的削除が使用されます。ディレクトリ内のすべてのファイルとサブディレクトリが削除されていることを確認してください。このメソッドを使用してディレクトリを削除する前に、階層型名前空間を有効にする必要があります。
            DeleteDirectoryRequest deleteDirectoryRequest = new DeleteDirectoryRequest(bucketName, directoryName);
            DeleteDirectoryResult deleteDirectoryResult = ossClient.deleteDirectory(deleteDirectoryRequest);

            // 削除されたディレクトリの絶対パス。
            System.out.println("delete dir name :" + deleteDirectoryResult.getDirectoryName());
            // 削除されたファイルとディレクトリの総数。
            System.out.println("delete number:" + deleteDirectoryResult.getDeleteNumber());
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

再帰的削除

再帰的削除を使用すると、ディレクトリとその中のすべてのファイルおよびサブディレクトリを削除できます。このメソッドは慎重に使用してください。

次のコードは、examplebucket バケットから指定されたディレクトリとその中のすべてのファイルおよびサブディレクトリを再帰的に削除する方法の例を示しています。

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

public class Demo {
    public static void main(String[] args) throws Exception {
        // 中国 (杭州) リージョンを例として使用します。他のリージョンについては、必要に応じて値を変更してください。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 環境変数からアクセス認証情報を取得します。サンプルコードを実行する前に、OSS_ACCESS_KEY_ID および OSS_ACCESS_KEY_SECRET 環境変数が設定されていることを確認してください。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // バケット名を指定します。例:examplebucket。
        String bucketName = "examplebucket";
        // ディレクトリの絶対パスを指定します。絶対パスにバケット名を含めることはできません。
        String directoryName = "exampledir";
        // 削除するディレクトリの完全なパスを指定します。完全なパスにバケット名を含めることはできません。
        final String prefix = "exampledir/";
        // バケットが配置されているリージョンを指定します。たとえば、バケットが中国 (杭州) リージョンにある場合は、Region を cn-hangzhou に設定します。
        String region = "cn-hangzhou";

        // OSSClient インスタンスを作成します。
        // OSSClient インスタンスが不要になったら、shutdown メソッドを呼び出してリソースを解放します。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // メソッド 1:listObjects の結果を走査して、ディレクトリとその中のすべてのファイルを削除します。
            String nextMarker = null;
            ObjectListing objectListing = null;
            do {
                ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName)
                        .withPrefix(prefix)
                        .withMarker(nextMarker);

                objectListing = ossClient.listObjects(listObjectsRequest);
                if (objectListing.getObjectSummaries().size() > 0) {
                    List<String> keys = new ArrayList<String>();
                    for (OSSObjectSummary s : objectListing.getObjectSummaries()) {
                        System.out.println("key name: " + s.getKey());
                        keys.add(s.getKey());
                    }
                    DeleteObjectsRequest deleteObjectsRequest = new DeleteObjectsRequest(bucketName).withKeys(keys).withEncodingType("url");
                    DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(deleteObjectsRequest);
                    List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
                    try {
                        for(String obj : deletedObjects) {
                            String deleteObj =  URLDecoder.decode(obj, "UTF-8");
                            System.out.println(deleteObj);
                        }
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }

                nextMarker = objectListing.getNextMarker();

//            // メソッド 2:deleteDirectory を呼び出してディレクトリを再帰的に削除します。このメソッドを使用してディレクトリを削除する前に、階層型名前空間を有効にする必要があります。このメソッドは中国本土のバケットには使用できません。
//            DeleteDirectoryRequest deleteDirectoryRequest = new DeleteDirectoryRequest(bucketName, directoryName);
//            deleteDirectoryRequest.setDeleteRecursive(true);
//            DeleteDirectoryResult deleteDirectoryResult = ossClient.deleteDirectory(deleteDirectoryRequest);
//
//            // 一度に最大 100 個のディレクトリとファイルを削除できます。一度にすべてのデータが削除されない場合、サーバーは nextDeleteToken を返します。その後、nextDeleteToken を使用して残りのデータの削除を続行できます。
//            // nextDeleteToken は、サーバーが次の削除の開始点を見つけるために使用されます。
//            String nextDeleteToken = deleteDirectoryResult.getNextDeleteToken();
//            System.out.println("delete next token:" + nextDeleteToken);
//            // nextDeleteToken を使用してディレクトリ内の残りのデータの削除を続行するには、次のコードを実行します。
//            deleteDirectoryRequest.setNextDeleteToken(nextDeleteToken);
//            deleteDirectoryResult = ossClient.deleteDirectory(deleteDirectoryRequest);

            // 削除されたディレクトリの絶対パス。
            //System.out.println("delete dir name :" + deleteDirectoryResult.getDirectoryName());
            // 削除されたファイルとディレクトリの総数。
            //System.out.println("delete number:" + deleteDirectoryResult.getDeleteNumber());

            } while (objectListing.isTruncated());
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

関連ドキュメント

  • ディレクトリの作成に使用される API 操作の詳細については、「PutObjectおよび「CreateDirectoryをご参照ください。

  • ディレクトリの名前変更に使用される API 操作の詳細については、「Rename」をご参照ください。

  • ディレクトリの削除に使用される API 操作の詳細については、「DeleteObjectおよび「DeleteDirectoryをご参照ください。