与传统文件系统中的层级结构不同,OSS内部使用扁平结构存储数据。即所有数据均以对象(Object)的形式保存在存储空间(Bucket)中。为方便管理,OSS控制台将所有以正斜线(/)结尾的对象显示为目录,实现类似于目录的基本功能。您可以通过目录的层次来组织文件,实现分组并简化权限管理。
注意事项
本文以华东1(杭州)外网Endpoint为例。如果您希望通过与OSS同地域的其他阿里云产品访问OSS,请使用内网Endpoint。关于OSS支持的Region与Endpoint的对应关系,请参见访问域名和数据中心。
本文以从环境变量读取访问凭证为例。如何配置访问凭证,请参见Java配置访问凭证。
本文以OSS域名新建OSSClient为例。如果您希望通过自定义域名、STS等方式新建OSSClient,请参见新建OSSClient。
创建目录
以下代码提供了创建目录的两种方式。
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 java.io.ByteArrayInputStream;
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";
// 填写通过方式一创建的目录名称。
String dirName = "exampledir/";
// 填写通过方式二创建的目录名称。
String dirName2 = "exampledir1/";
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
try {
// 方式一:通过createDirectory接口直接创建目录。使用该方法创建目录前,需要开启分层命名空间。
ossClient.createDirectory(bucketName, dirName);
// 方式二:通过上传空字符串的形式创建目录。
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.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.*;
public class Demo {
public static void main(String[] args) throws Exception {
// yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
String endPoint = "yourEndpoint";
// 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// 填写Bucket名称,例如examplebucket。
String bucketName = "examplebucket";
// 填写源目录绝对路径。目录绝对路径中不能包含Bucket名称。
String sourceDir = "exampledir";
// 填写与源目录处于同一Bucket中的目标目录绝对路径。目录绝对路径中不能包含Bucket名称。
String destinationDir = "newexampledir";
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endPoint, credentialsProvider);
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.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.*;
public class Demo {
public static void main(String[] args) throws Exception {
// yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
String endPoint = "yourEndpoint";
// 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// 填写Bucket名称。
String bucketName = "examplebucket";
// 填写目录绝对路径。目录绝对路径中不能包含Bucket名称。
String directoryName = "exampledir";
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endPoint, credentialsProvider);
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.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";
// 填写目录绝对路径。目录绝对路径中不能包含Bucket名称。
String directoryName = "exampledir";
// 填写待删除目录的完整路径,完整路径中不包含Bucket名称。
final String prefix = "exampledir/";
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
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递归删除方式删除目录。使用该方法删除目录前,需要开启分层命名空间(中国内地的bucket无法使用)。
// 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。