文档

Java重命名文件

更新时间:

OSS不支持直接对文件(Object)进行重命名。如果您需要在同一个Bucket内对Object进行重命名,您可以通过CopyObject接口将源Object拷贝至目标Object,然后通过DeleteObject接口删除源Object。

注意事项

  • 本文以华东1(杭州)外网Endpoint为例。如果您希望通过与OSS同地域的其他阿里云产品访问OSS,请使用内网Endpoint。关于OSS支持的Region与Endpoint的对应关系,请参见访问域名和数据中心

  • 本文以从环境变量读取访问凭证为例。如何配置访问凭证,请参见Java配置访问凭证

  • 本文以OSS域名新建OSSClient为例。如果您希望通过自定义域名、STS等方式新建OSSClient,请参见新建OSSClient

示例代码

以下代码用于将examplebucket下的srcobject.txt重命名为destobject.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名称。
        String bucketName = "examplebucket";
        // 填写源Object的完整路径,完整路径中不能包含Bucket名称。
        String sourceKey = "srcobject.txt";
        // 填写目标Object的完整路径。Object完整路径中不能包含Bucket名称。
        String destinationKey = "destobject.txt";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);

        try {
            // 将examplebucket下的srcobject.txt拷贝至同一Bucket下的destobject.txt。
            ossClient.copyObject(bucketName, sourceKey, bucketName, destinationKey);

            // 删除srcobject.txt。
            ossClient.deleteObject(bucketName, sourceKey);
        } 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();
            }
        }
    }
}
说明

OSS也不支持直接对目录进行重命名。如果需要重命名目录,您可以参考以上示例对该目录下的子目录和Object逐个进行重命名操作。

相关文档

关于重命名文件涉及的API接口说明,请分别参见CopyObjectDeleteObject

  • 本页导读 (1)
文档反馈