您可以根据需要删除单个文件(Object)、删除指定的多个文件、删除指定前缀的文件或者删除指定目录及目录下的所有文件。
请您谨慎使用删除操作,文件删除后将无法恢复。
注意事项
-
本文以华东 1(杭州)外网 Endpoint 为例。如果您希望通过与 OSS 同地域的其他阿里云产品访问 OSS,请使用内网 Endpoint。关于 OSS 支持的 Region 与 Endpoint 的对应关系,请参见 OSS 访问域名、数据中心、开放端口 。
-
本文以从环境变量读取访问凭证为例。如何配置访问凭证,请参见 Java 配置访问凭证 。
-
本文以 OSS 域名新建 OSSClient 为例。如果您希望通过自定义域名、STS 等方式新建 OSSClient,请参见 新建 OSSClient 。
-
要删除文件,您必须具有
oss:DeleteObject权限。具体操作,请参见 为 RAM 用户授权自定义的权限策略 。
删除单个文件
以下代码用于删除 examplebucket 中的 exampleobject.txt 文件。
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";
// 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// 填写Bucket名称,例如examplebucket。
String bucketName = "examplebucket";
// 填写文件完整路径。文件完整路径中不能包含Bucket名称。
String objectName = "exampleobject.txt";
// 填写Bucket所在地域。以华东1(杭州)为例,Region填写为cn-hangzhou。
String region = "cn-hangzhou";
// 创建OSSClient实例。
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();
}
批量删除文件
手动删除文件时,每次最多删除 1000 个文件。您可以删除指定的多个文件、删除指定前缀的文件或者删除指定目录及目录下的所有文件。
OSS 还支持通过设置生命周期规则来自动删除文件。更多信息,请参见 基于最后一次修改时间的生命周期规则 。
批量删除文件的参数说明
-
请求参数
参数
描述
方法
Keys
需要删除的文件。
setKeys(List<String>)
quiet
返回结果包括如下两种模式,默认返回模式为详细模式,请根据实际选择返回模式。
-
详细模式(verbose):未设置 quiet 或者设置 quiet 为 false,表示返回所有删除的文件列表。
-
简单模式(quiet):设置 quiet 为 true 时,OSS 不返回消息体。
setQuiet(boolean)
encodingType
对返回的文件名称进行编码。编码类型目前仅支持 URL。
setEncodingType(String)
-
-
返回参数
参数
描述
方法
deletedObjects
删除结果。
-
详细模式:返回删除成功的文件列表,包括删除不存在的文件。
-
简单模式:不返回任何消息体。
List<String> getDeletedObjects()
encodingType
deletedObjects 中文件名称的编码,返回为空表示没有编码。
getEncodingType()
-
删除指定名称的多个文件
以下代码用于删除指定名称的多个文件。
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.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 {
// Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// 填写Bucket名称,例如examplebucket。
String bucketName = "examplebucket";
// 填写Bucket所在地域。以华东1(杭州)为例,Region填写为cn-hangzhou。
String region = "cn-hangzhou";
// 创建OSSClient实例。
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// 删除文件。
// 填写需要删除的多个文件完整路径。文件完整路径中不能包含Bucket名称。
List<String> keys = new ArrayList<String>();
keys.add("exampleobjecta.txt");
keys.add("testfolder/sampleobject.txt");
keys.add("exampleobjectb.txt");
DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(new DeleteObjectsRequest(bucketName).withKeys(keys).withEncodingType("url"));
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();
} 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 的值为空字符串或者 NULL,将会删除整个 Bucket 内的所有文件,请谨慎使用。
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.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 {
// Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// 填写Bucket名称,例如examplebucket。
String bucketName = "examplebucket";
// 如果您需要删除所有前缀为src的文件,则prefix设置为src。设置为src后,所有前缀为src的非目录文件、src目录以及目录下的所有文件均会被删除。
String prefix = "src";
// 如果您仅需要删除src目录及目录下的所有文件,则prefix设置为src/。
// String prefix = "src/";
// 填写Bucket所在地域。以华东1(杭州)为例,Region填写为cn-hangzhou。
String region = "cn-hangzhou";
// 创建OSSClient实例。
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// 列举所有包含指定前缀的文件并删除。
String nextMarker = null;
ObjectListing objectListing = null;
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();
} 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();
}
常见问题
使用 Java SDK 删除单个文件后,如何确定文件是否已成功删除?
在
OSS Java SDK
中使用
OSSClient
的
deleteObject
方法删除单个文件时,如果该方法没有抛出异常,则说明已成功删除该文件。如果您需要进一步确认该文件是否已成功删除,可以调用
OSSClient
的
doesObjectExist
方法,该方法可以判断指定的文件是否存在。如果该方法返回
false
,则说明该文件已成功删除。更多信息,请参见
判断文件是否存在
。
相关文档
-
删除单个文件
关于删除单个文件的 API 接口说明,请参见 DeleteObject 。
-
删除多个文件
-
关于删除多个文件的完整示例代码,请参见 GitHub 示例 。
-
关于删除多个文件的 API 接口说明,请参见 DeleteMultipleObjects 。
-