Java刪除文件
本文介紹如何在受版本控制的存儲空間(Bucket)中刪除單個或多個文件(Object))以及指定前綴的(Prefix)的文件。
注意事項
本文以華東1(杭州)外網(wǎng)Endpoint為例。如果您希望通過與OSS同地域的其他阿里云產(chǎn)品訪問OSS,請使用內(nèi)網(wǎng)Endpoint。關(guān)于OSS支持的Region與Endpoint的對應關(guān)系,請參見OSS訪問域名、數(shù)據(jù)中心、開放端口。
本文以從環(huán)境變量讀取訪問憑證為例。如何配置訪問憑證,請參見Java配置訪問憑證。
本文以OSS域名新建OSSClient為例。如果您希望通過自定義域名、STS等方式新建OSSClient,請參見新建OSSClient。
要刪除文件,您必須有
oss:DeleteObject
權(quán)限。具體操作,請參見為RAM用戶授權(quán)自定義的權(quán)限策略。
版本控制下的刪除行為
版本控制下的刪除行為說明如下:
未指定versionId(臨時刪除):
如果在未指定versionId的情況下執(zhí)行刪除操作時,默認不會刪除Object的當前版本,而是對當前版本插入刪除標記(Delete Marker)。當執(zhí)行GetObject操作時,OSS會檢測到當前版本為刪除標記,并返回
404 Not Found
。此外,響應中會返回header:x-oss-delete-marker = true
以及新生成的刪除標記的版本號x-oss-version-id
。x-oss-delete-marker
的值為true,表示與返回的x-oss-version-id
對應的版本為刪除標記。指定versionId(永久刪除):
如果在指定versionId的情況下執(zhí)行刪除操作時,OSS會根據(jù)
params
中指定的versionId
參數(shù)永久刪除該版本。如果要刪除ID為“null”的版本,請在params
參數(shù)中添加params['versionId'] = “null”
,OSS將“null”字符串當成“null”的versionId,從而刪除versionId為“null”的Object。
刪除單個文件
以下提供了永久刪除及臨時刪除單個Object的示例。
永久刪除
以下代碼用于指定versionId對Object進行永久刪除:
import com.aliyun.oss.ClientException; import com.aliyun.oss.OSS; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.OSSException; public class Demo { public static void main(String[] args) throws Exception { // Endpoint以華東1(杭州)為例,其它Region請按實際情況填寫。 String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // 從環(huán)境變量中獲取訪問憑證。運行本代碼示例之前,請確保已設置環(huán)境變量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。 EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // 填寫Bucket名稱,例如examplebucket。 String bucketName = "examplebucket"; // 填寫Object的完整路徑。Object完整路徑中不能包含Bucket名稱。 String objectName = "exampledir/object"; String versionId = "CAEQMxiBgICAof2D0BYiIDJhMGE3N2M1YTI1NDQzOGY5NTkyNTI3MGYyMzJm****"; // 填寫Bucket所在地域。以華東1(杭州)為例,Region填寫為cn-hangzhou。 String region = "cn-hangzhou"; // 創(chuàng)建OSSClient實例。 ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endpoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { // 刪除指定版本的Object。 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(); } } } }
臨時刪除
以下代碼用于不指定versionId對Object進行臨時刪除:
import com.aliyun.oss.ClientException; import com.aliyun.oss.OSS; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.OSSException; public class Demo { public static void main(String[] args) throws Exception { // Endpoint以華東1(杭州)為例,其它Region請按實際情況填寫。 String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // 從環(huán)境變量中獲取訪問憑證。運行本代碼示例之前,請確保已設置環(huán)境變量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。 EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // 填寫Bucket名稱,例如examplebucket。 String bucketName = "examplebucket"; // 填寫Object的完整路徑。Object完整路徑中不能包含Bucket名稱。 String objectName = "exampledir/object"; // 創(chuàng)建OSSClient實例。 OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider); try { // 開啟版本控制狀態(tài)下,此方法為臨時刪除,將會給Object添加刪除標記。 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(); } } } }
刪除多個文件
以下提供了永久刪除以及臨時刪除多個Object的示例。
永久刪除
以下代碼用于指定versionId對多個Object及刪除標記進行永久刪除:
import com.aliyun.oss.ClientException; import com.aliyun.oss.OSS; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.OSSException; 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 { // Endpoint以華東1(杭州)為例,其它Region請按實際情況填寫。 String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // 從環(huán)境變量中獲取訪問憑證。運行本代碼示例之前,請確保已設置環(huán)境變量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。 EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // 填寫Bucket名稱,例如examplebucket。 String bucketName = "examplebucket"; // 填寫Object的完整路徑。Object完整路徑中不能包含Bucket名稱。 String objectName = "exampledir/object"; String object2Name = "exampledir/object2"; String yourObjectNameVersionId = "CAEQMxiBgICAof2D0BYiIDJhMGE3N2M1YTI1NDQzOGY5NTkyNTI3MGYyMzJm****"; String yourObject2DelMarkerNameVersionId = "MGE3N2M1YgICAof2D0BYiID3N2M1YTITI1NDQzOGY5NTN2M1YTI1NDQz****"; // 創(chuàng)建OSSClient實例。 OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider); try { // 刪除指定版本的Object與刪除標記。 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); // 發(fā)起deleteVersions請求。 DeleteVersionsResult delVersionsResult = ossClient.deleteVersions(delVersionsRequest); // 查看刪除結(jié)果。 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(); } } } }
臨時刪除
以下代碼用于不指定versionId對多個Object進行臨時刪除:
import com.aliyun.oss.ClientException; import com.aliyun.oss.OSS; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.OSSException; 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 { // Endpoint以華東1(杭州)為例,其它Region請按實際情況填寫。 String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // 從環(huán)境變量中獲取訪問憑證。運行本代碼示例之前,請確保已設置環(huán)境變量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。 EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // 填寫Bucket名稱,例如examplebucket。 String bucketName = "examplebucket"; // 填寫Object的完整路徑。Object完整路徑中不能包含Bucket名稱。 String objectName = "exampledir/object"; String object2Name = "exampledir/object2"; // 創(chuàng)建OSSClient實例。 OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider); try { // 批量刪除Object。 List<String> KeysList = new ArrayList<String>(); KeysList.add(objectName); KeysList.add(object2Name); DeleteObjectsRequest request = new DeleteObjectsRequest(bucketName); request.setKeys(KeysList); // 發(fā)起deleteObjects請求。 DeleteObjectsResult delObjResult = ossClient.deleteObjects(request); // 查看刪除結(jié)果。 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(); } } } }
刪除指定前綴(prefix)的文件
以下代碼用于刪除指定前綴的文件:
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import java.util.ArrayList;
import java.util.List;
public class Demo {
public static void main(String[] args) throws Exception {
// Endpoint以華東1(杭州)為例,其它Region請按實際情況填寫。
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// 從環(huán)境變量中獲取訪問憑證。運行本代碼示例之前,請確保已設置環(huán)境變量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// 填寫B(tài)ucket名稱,例如examplebucket。
String bucketName = "examplebucket";
// 指定前綴。
String prefix = "yourkeyPrefix";
// 創(chuàng)建OSSClient實例。
OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
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();
}
}
}
}
相關(guān)文檔
關(guān)于刪除單個文件的API接口說明,請參見DeleteObject。
關(guān)于刪除多個文件的API接口說明,請參見DeleteMultipleObjects。