Object Storage Service (OSS) uses a flat structure instead of a hierarchical structure which is used by traditional file systems to store objects. All data in OSS is stored as objects in buckets. You can use directories in OSS to help you categorize objects and control access to your objects in a simplified manner.

Usage notes

  • In this topic, the public endpoint of the China (Hangzhou) region is used. If you want to access OSS by using other Alibaba Cloud services in the same region as OSS, use an internal endpoint. For more information about the regions and endpoints supported by OSS, see Regions and endpoints.
  • In this topic, an OSSClient instance is created by using an OSS endpoint. If you want to create an OSSClient by using custom domain names or STS, see Create an OSSClient instance.

Create a directory

The following sample code provides an example on how to create a directory:

The following sample code provides examples on how to create a directory by using two different methods:

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
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 {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
        String accessKeyId = "yourAccessKeyId";
        String accessKeySecret = "yourAccessKeySecret";
        // Specify the name of the bucket. 
        String bucketName = "examplebucket";
        // Specify the name of the directory to be created by using Method 1. 
        String dirName = "exampledir/";
        // Specify the name of the directory to be created by using Method 2. 
        String dirName2 = "exampledir1/";

        // Create an OSSClient instance. 
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // Method 1: Create a directory directly by calling the createDirectory operation. // Before you create the directory, enable the hierarchical namespace feature for the bucket. 
            ossClient.createDirectory(bucketName, dirName);

            // Method 2: Create a directory by uploading an empty string. 
            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();
            }
        }
    }
}

Rename a directory

After the hierarchical namespace feature is enabled for a bucket, you can rename directories in the bucket.

The following sample code provides an example on how to rename the exampledir directory in the examplebucket bucket to newexampledir:

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
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 {
        // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
        String endPoint = "yourEndpoint";
        // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
        String accessKeyId = "yourAccessKeyId";
        String accessKeySecret = "yourAccessKeySecret";
        // Specify the name of the bucket. 
        String bucketName = "examplebucket";
        // Specify the absolute path of the source directory. The absolute path of the directory cannot contain the bucket name. 
        String sourceDir = "exampledir";
        // Specify the absolute path of the destination directory that is in the same bucket as the source directory. The absolute path of the directory cannot contain the bucket name. 
        String destinationDir = "newexampledir";

        // Create an OSSClient instance. 
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);

        try {
            // Change the absolute path of the source directory to that of the destination directory. 
            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();
            }
        }
    }
}

Delete a directory

Warning If you delete a directory, the subdirectories and all objects in the directory are synchronously deleted. Proceed with caution.

You can use the non-recursive delete or recursive delete method to delete a specified directory from a bucket.

  • Non-recursive delete

    If you use the non-recursive delete method to delete a directory, you can delete the directory only when the directory is empty.

    The following sample code provides an example on how to use the non-recursive delete method to delete the exampledir directory from the examplebucket bucket:

    import com.aliyun.oss.ClientException;
    import com.aliyun.oss.OSS;
    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 {
            // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
            String endPoint = "yourEndpoint";
            // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
            String accessKeyId = "yourAccessKeyId";
            String accessKeySecret = "yourAccessKeySecret";
            // Specify the name of the bucket. 
            String bucketName = "examplebucket";
            // Specify the absolute path of the directory. The absolute path of the directory cannot contain the bucket name. 
            String directoryName = "exampledir";
    
            // Create an OSSClient instance. 
            OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
    
            try {
                // Delete the directory. By default, the non-recursive delete method is used. Make sure that all objects and subdirectories are deleted from this directory. Before you use this method to delete a directory, you must enable the hierarchical namespace feature. 
                DeleteDirectoryRequest deleteDirectoryRequest = new DeleteDirectoryRequest(bucketName, directoryName);
                DeleteDirectoryResult deleteDirectoryResult = ossClient.deleteDirectory(deleteDirectoryRequest);
    
                // Display the absolute path of the deleted directory. 
                System.out.println("delete dir name :" + deleteDirectoryResult.getDirectoryName());
                // Display the total number of deleted objects and directories. 
                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();
                }
            }
        }
    }
  • Recursive delete

    If you use the recursive delete method to delete a directory, the objects and subdirectories in the directory are also deleted. Proceed with caution.

    The following sample code provides an example on how to use the recursive delete method to delete a specified directory and the objects and subdirectories in the directory from the examplebucket bucket:

    import com.aliyun.oss.ClientException;
    import com.aliyun.oss.OSS;
    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 {
            // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
            String accessKeyId = "yourAccessKeyId";
            String accessKeySecret = "yourAccessKeySecret";
            // Specify the name of the bucket. 
            String bucketName = "examplebucket";
            // Specify the absolute path of the directory. The absolute path of the directory cannot contain the bucket name. 
            String directoryName = "exampledir";
            // Specify the full path of the directory that you want to delete. The full path of the directory cannot contain the bucket name. 
            final String prefix = "log/";
    
            // Create an OSSClient instance. 
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    
            try {
                // Method 1: Use the deleteDirectory recursive deletion method to delete directories. Before you use this method to delete a directory, you must enable the hierarchical namespace feature. 
                DeleteDirectoryRequest deleteDirectoryRequest = new DeleteDirectoryRequest(bucketName, directoryName);
                deleteDirectoryRequest.setDeleteRecursive(true);
                DeleteDirectoryResult deleteDirectoryResult = ossClient.deleteDirectory(deleteDirectoryRequest);
    
                // Display the deletion result. 
                // You can delete up to 100 directories and objects at a time. If only part of directories and objects are returned, the server returns nextDeleteToken. You can use nextDeleteToken to continue deleting remaining data. 
                // nextDeleteToken helps the server find the object or directory after which the delete operation begins. 
                String nextDeleteToken = deleteDirectoryResult.getNextDeleteToken();
                System.out.println("delete next token:" + nextDeleteToken);
                // Display the absolute path of the deleted directory. 
                System.out.println("delete dir name :" + deleteDirectoryResult.getDirectoryName());
                // Display the total number of deleted objects and directories. 
                System.out.println("delete number:" + deleteDirectoryResult.getDeleteNumber());
    
    
                // Method 2: Use the listObjects traverse deletion method to delete the directory and all objects in the directory. 
                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();
                } 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();
                }
            }
        }
    }

References

  • For more information about the API operation that you can call to create a directory, see PutObject and CreateDirectory.
  • For more information about the API operation that you can call to rename a directory, see Rename.
  • For more information about the API operation that you can call to delete a directory, see DeleteObject and DeleteDirectory.