このトピックでは、バージョン管理が有効なバケットから、単一のオブジェクト、複数のオブジェクト、または指定されたプレフィックスを持つオブジェクトを削除する方法について説明します。
注意事項
このトピックでは、中国 (杭州) リージョンのパブリックエンドポイントを使用します。同じリージョン内の他の Alibaba Cloud サービスから OSS にアクセスするには、内部エンドポイントを使用します。サポートされているリージョンとエンドポイントの詳細については、「リージョンとエンドポイント」をご参照ください。
このトピックでは、アクセス認証情報は環境変数から取得されます。アクセス認証情報の設定方法の詳細については、「アクセス認証情報の設定」をご参照ください。
このトピックでは、OSS エンドポイントを使用して OSSClient インスタンスを作成します。カスタムドメイン名またはセキュリティトークンサービス (STS) を使用して OSSClient インスタンスを作成する場合は、「一般的なシナリオの設定例」をご参照ください。
オブジェクトを削除するには、
oss:DeleteObject権限が必要です。詳細については、「RAM ユーザーへのカスタムアクセスポリシーの付与」をご参照ください。
バージョン管理が有効なバケットでの削除動作
バージョン管理が有効なバケットでの削除動作は次のとおりです:
バージョン ID を指定しない削除 (一時的な削除):
バージョン ID を指定せずにオブジェクトを削除した場合、OSS はオブジェクトを完全に削除しません。代わりに、OSS は削除マーカーを追加し、それがオブジェクトのカレントバージョンになります。オブジェクトを取得しようとすると、OSS は削除マーカーを検出し、
404 Not Foundエラーを返します。応答には、header:x-oss-delete-marker = trueと、x-oss-version-id内の新しい削除マーカーのバージョン ID が含まれます。x-oss-delete-markerの値が true の場合、返されたx-oss-version-idに対応するバージョンが削除マーカーであることを示します。バージョン ID を指定した削除 (完全な削除):
削除操作で `versionId` を指定すると、OSS は
paramsパラメーターで指定されたversionIdのオブジェクトバージョンを完全に削除します。`versionId` が文字列 "null" のオブジェクトバージョンを削除するには、paramsパラメーターにparams['versionId'] = "null"を追加します。この場合、OSS は文字列 "null" を `versionId` として扱い、対応するオブジェクトバージョンを削除します。
単一オブジェクトの削除
次の例は、単一のオブジェクトを完全にまたは一時的に削除する方法を示しています。
完全な削除
次のコードは、バージョン 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 { // 指定されたバージョンのオブジェクトと削除マーカーを削除します。 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」をご参照ください。