All Products
Search
Document Center

Object Storage Service:Manage directories by using OSS SDK for Java

Last Updated:Sep 02, 2024

Object Storage Service (OSS) uses a flat structure instead of a hierarchical structure that is used by traditional file systems to store objects. All data in OSS is stored as objects in buckets. To facilitate object management, the OSS console displays objects whose names end with a forward slash (/) as directories. Directories are similar to folders in file systems. You can use directories to hierarchically organize and group objects and facilitate access control.

Usage notes

  • In this topic, the public endpoint of the China (Hangzhou) region is used. If you want to access OSS from other Alibaba Cloud services in the same region as OSS, use an internal endpoint. For more information about OSS regions and endpoints, see Regions and endpoints.

  • In this topic, access credentials are obtained from environment variables. For more information about how to configure access credentials, see Configure access credentials.

  • In this topic, an OSSClient instance is created by using an OSS endpoint. If you want to create an OSSClient instance by using custom domain names or Security Token Service (STS), see Create an OSSClient instance.

Create a directory

The following sample code provides two methods to create a directory.

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 {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the name of the directory that you want to create by using Method 1. 
        String dirName = "exampledir/";
        // Specify the name of the directory that you want to create by using Method 2. 
        String dirName2 = "exampledir1/";

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

        try {
            // Method 1: Call the createDirectory operation to create a directory. Before you use this method to create a directory, you must enable the hierarchical namespace feature. 
            ossClient.createDirectory(bucketName, dirName);

            // Method 2: Upload an empty string to create a directory. 
            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.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 {
        // 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";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the absolute path of the source directory. Do not include the bucket name in the absolute path. 
        String sourceDir = "exampledir";
        // Specify the absolute path of the destination directory that is in the same bucket as the source directory. Do not include the bucket name in the absolute path. 
        String destinationDir = "newexampledir";

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

        try {
            // Change the absolute path of the source directory to the path 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. We recommend that you exercise caution when you delete a directory.

You can use the non-recursive delete or recursive delete method to delete a specific 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.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 {
        // 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";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. 
        String bucketName = "examplebucket";
        // Specify the absolute path of the directory. Do not include the bucket name in the absolute path. 
        String directoryName = "exampledir";

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

        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 specific 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.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 {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the absolute path of the directory. Do not include the bucket name in the absolute path. 
        String directoryName = "exampledir";
        // Specify the full path of the directory that you want to delete. Do not include the bucket name in the full path. 
        final String prefix = "exampledir/";

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

        try {
            // Method 1: Call the listObjects operation to traverse and 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();

//            // Method 2: Call the deleteDirectory operation to delete a directory. Before you use this method to delete a directory, you must enable the hierarchical namespace feature. The hierarchical namespace feature is not available in regions within the Chinese mainland. 
//            DeleteDirectoryRequest deleteDirectoryRequest = new DeleteDirectoryRequest(bucketName, directoryName);
//            deleteDirectoryRequest.setDeleteRecursive(true);
//            DeleteDirectoryResult deleteDirectoryResult = ossClient.deleteDirectory(deleteDirectoryRequest);
//
//            // You can delete up to 100 directories and objects at a time. If only part of directories and objects are deleted, the server returns nextDeleteToken. You can use nextDeleteToken to continue deleting the remaining data. 
//            // nextDeleteToken helps the server find the object or directory from which the next delete operation begins. 
//            String nextDeleteToken = deleteDirectoryResult.getNextDeleteToken();
//            System.out.println("delete next token:" + nextDeleteToken);
//            // If you need to use nextDeleteToken to continue to delete the remaining data in the directory, run the following code:
//            deleteDirectoryRequest.setNextDeleteToken(nextDeleteToken);
//            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());

            } 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 operations 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 operations that you can call to delete a directory, see DeleteObject and DeleteDirectory.