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

Object Storage Service:オブジェクトの削除 (OSS SDK for Java 1.0)

最終更新日:Mar 19, 2026

このトピックでは、バージョン管理が有効な Object Storage Service (OSS) バケットから、単一のオブジェクト、複数のオブジェクト、または特定のプレフィックスを含む名前のオブジェクトを削除する方法について説明します。

注意事項

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

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

  • このトピックでは、OSS エンドポイントを使用して OSSClient インスタンスを作成する方法を示します。カスタムドメインの使用や Security Token Service (STS) からの認証情報による認証など、代替の構成については、「クライアント構成」をご参照ください。

  • バージョン管理が有効になった後、オブジェクトを削除するには oss:DeleteObjectVersion 権限が必要です。詳細については、「RAM ユーザーへのカスタムポリシーのアタッチ」をご参照ください。

バージョン管理が有効なバケットでの削除操作

バージョン管理が有効なバケットでの削除動作は次のとおりです。

  • バージョン ID を指定しない削除 (一時的な削除):

    オブジェクトのバージョン ID を指定せずに削除すると、OSS はオブジェクトの現在のバージョンを削除しません。代わりに、最新バージョンとして削除マーカーを追加します。GetObject を呼び出すと、OSS は現在のバージョンが削除マーカーであることを検出し、404 Not Found を返します。応答には、header: x-oss-delete-marker = true と、新しい削除マーカーのバージョン ID が x-oss-version-id に含まれます。

    x-oss-delete-marker が true の場合、x-oss-version-id で返されるバージョン ID は削除マーカーに対応します。

  • バージョン ID を指定した削除 (永続的な削除):

    オブジェクトを削除する際にバージョン ID を指定すると、OSS は params パラメーター versionId に基づいてそのバージョンを永続的に削除します。ID が "null" のバージョンを削除するには、paramsparams['versionId'] = "null" を追加します。OSS は文字列 "null" をバージョン ID として扱い、ID が "null" のオブジェクトバージョンを削除します。

単一ファイルの削除

次の例は、単一のオブジェクトを永続的または一時的に削除する方法を示しています。

  • 永続的な削除

    次のコードは、バージョン ID を指定してオブジェクトを永続的に削除します。

    import com.aliyun.oss.*;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.common.comm.SignVersion;
    
    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 objectName = "exampledir/object";
            String versionId  = "CAEQMxiBgICAof2D0BYiIDJhMGE3N2M1YTI1NDQzOGY5NTkyNTI3MGYyMzJm****";
            // バケットが配置されているリージョンを指定します。たとえば、バケットが中国 (杭州) リージョンに配置されている場合、リージョンを 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 {
                // オブジェクトの指定されたバージョンを削除します。
                ossClient.deleteVersion(bucketName, objectName , versionId);
            } 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();
                }
            }
        }
    }
  • 一時的な削除

    次のコードは、バージョン ID を指定せずにオブジェクトを一時的に削除します。

    import com.aliyun.oss.*;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.common.comm.SignVersion;
    
    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 objectName = "exampledir/object";
            // バケットが配置されているリージョンを指定します。たとえば、バケットが中国 (杭州) リージョンに配置されている場合、リージョンを 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 {
                // オブジェクトを一時的に削除します。オブジェクトに削除マーカーが追加されます。
                ossClient.deleteObject(bucketName, objectName);
            } 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();
                }
            }
        }
    }

複数のオブジェクトの削除

次の例は、複数のオブジェクトを永続的または一時的に削除する方法を示しています。

  • 永続的な削除

    次のコードは、バージョン ID を指定して複数のオブジェクトまたは削除マーカーを永続的に削除します。

    import com.aliyun.oss.*;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.common.comm.SignVersion;
    import com.aliyun.oss.model.DeleteVersionsRequest;
    import com.aliyun.oss.model.DeleteVersionsResult;
    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 objectName = "exampledir/object";
            String object2Name = "exampledir/object2";
            String yourObjectNameVersionId  = "CAEQMxiBgICAof2D0BYiIDJhMGE3N2M1YTI1NDQzOGY5NTkyNTI3MGYyMzJm****";
            String yourObject2DelMarkerNameVersionId  = "MGE3N2M1YgICAof2D0BYiID3N2M1YTITI1NDQzOGY5NTN2M1YTI1NDQz****";
    
            // バケットが配置されているリージョンを指定します。たとえば、バケットが中国 (杭州) リージョンに配置されている場合、リージョンを 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 {
                // 指定されたバージョン ID を持つオブジェクトまたは削除マーカーを削除します。
                List<DeleteVersionsRequest.KeyVersion> keyVersionsList = new ArrayList<DeleteVersionsRequest.KeyVersion>();
                keyVersionsList.add(new DeleteVersionsRequest.KeyVersion(objectName,yourObjectNameVersionId));
                keyVersionsList.add(new DeleteVersionsRequest.KeyVersion(object2Name,yourObject2DelMarkerNameVersionId));
                DeleteVersionsRequest delVersionsRequest = new DeleteVersionsRequest(bucketName);
                delVersionsRequest.setKeys(keyVersionsList);
                // deleteVersions リクエストを開始します。
                DeleteVersionsResult delVersionsResult = ossClient.deleteVersions(delVersionsRequest);
    
                // 削除結果を表示します。
                for (DeleteVersionsResult.DeletedVersion delVer : delVersionsResult.getDeletedVersions()) {
                    String keyName = URLDecoder.decode(delVer.getKey(), "UTF-8");
                    String keyVersionId = delVer.getVersionId();
                    String keyDelMarkerId = delVer.getDeleteMarkerVersionId();
                    System.out.println("delete key: " + keyName);
                    System.out.println("delete key versionId: " + keyVersionId);
                    if(keyDelMarkerId != null && keyDelMarkerId.length() != 0){
                        System.out.println("delete key del_marker versionId: " + keyDelMarkerId);
                    }
                }
            } 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();
                }
            }
        }
    }
  • 一時的な削除

    次のコードは、バージョン ID を指定せずに複数のオブジェクトを一時的に削除します。

    import com.aliyun.oss.*;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.common.comm.SignVersion;
    import com.aliyun.oss.model.DeleteObjectsRequest;
    import com.aliyun.oss.model.DeleteObjectsResult;
    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 objectName = "exampledir/object";
            String object2Name = "exampledir/object2";
    
            // バケットが配置されているリージョンを指定します。たとえば、バケットが中国 (杭州) リージョンに配置されている場合、リージョンを 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 {
                // 複数のオブジェクトを一度に削除します。
                List<String> KeysList = new ArrayList<String>();
                KeysList.add(objectName);
                KeysList.add(object2Name);
                DeleteObjectsRequest request = new DeleteObjectsRequest(bucketName);
                request.setKeys(KeysList);
                // deleteObjects リクエストを開始します。
                DeleteObjectsResult delObjResult = ossClient.deleteObjects(request);
    
                // 削除結果を表示します。
                for (String o : delObjResult.getDeletedObjects()) {
                    String keyName = URLDecoder.decode(o, "UTF-8");
                    System.out.println("delete key name: " + keyName);
                }
            } 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();
                }
            }
        }
    }

特定のプレフィックスを含む名前のオブジェクトの削除

次のコードは、指定されたプレフィックスを含む名前のすべてのオブジェクトを削除します。

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;
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 prefix = "yourkeyPrefix";

        // バケットが配置されているリージョンを指定します。たとえば、バケットが中国 (杭州) リージョンに配置されている場合、リージョンを 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 {
            // 指定されたプレフィックスを含む名前のオブジェクトのすべてのバージョンをリストし、それらを削除します。
            String nextKeyMarker = null;
            String nextVersionMarker = null;
            VersionListing versionListing = null;
            do {
                ListVersionsRequest listVersionsRequest = new ListVersionsRequest()
                        .withBucketName(bucketName)
                        .withKeyMarker(nextKeyMarker)
                        .withVersionIdMarker(nextVersionMarker)
                        .withPrefix(prefix);

                versionListing = ossClient.listVersions(listVersionsRequest);
                if (versionListing.getVersionSummaries().size() > 0) {
                    List<DeleteVersionsRequest.KeyVersion> keyVersionsList = new ArrayList<DeleteVersionsRequest.KeyVersion>();
                    for (OSSVersionSummary ossVersion : versionListing.getVersionSummaries()) {
                        System.out.println("key name: " + ossVersion.getKey());
                        System.out.println("versionid: " + ossVersion.getVersionId());
                        System.out.println("Is delete marker: " + ossVersion.isDeleteMarker());
                        keyVersionsList.add(new DeleteVersionsRequest.KeyVersion(ossVersion.getKey(), ossVersion.getVersionId()));
                    }
                    DeleteVersionsRequest delVersionsRequest = new DeleteVersionsRequest(bucketName).withKeys(keyVersionsList);
                    ossClient.deleteVersions(delVersionsRequest);
                }

                nextKeyMarker = versionListing.getNextKeyMarker();
                nextVersionMarker = versionListing.getNextVersionIdMarker();
            } while (versionListing.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 オペレーションの詳細については、「DeleteObject」をご参照ください。

  • 複数のオブジェクトを削除するために呼び出すことができる API オペレーションの詳細については、「DeleteMultipleObjects」をご参照ください。