今天的项目需要用腾讯云来做云存储服务,刚开始一头雾水,后来看了Java的API文档和SDK文档才慢慢有个了解,这次作下记录,方便以后查看。

本地环境依赖

SDK 支持 JDK 1.7, 1.8 及以上版本。

安装 SDK(maven 安装)

<dependency>
            <groupId>com.qcloud</groupId>
            <artifactId>cos_api</artifactId>
            <version>5.4.6</version>
</dependency>

注册好腾讯云账号,在腾讯云上复制这四个在代码里替换即可,ACCESSKEY,SECRETKEY,APPID,REGIONID

\"在这里插入图片描述\"创建存储桶
\"在这里插入图片描述\"上传上来的文件
\"在这里插入图片描述\"

初始化密钥信息

    private static final String ACCESSKEY = \"XXXXXX\";
    private static final String SECRETKEY = \"XXXXXX\";
    private static final String BUCKETNAME = \"XXXXXX-12517827811\";
    private static final String APPID = \"12517827811 \";
    private static final String REGIONID = \"ap-guangzhou\";
    private static final String KEY=\"MyFile1/zookeeper-3.4.8.tar.gz\";
    private static final String KEY01=\"MyFile1/1.jpg\";

初始化客户端

       // 1 初始化用户身份信息(secretId, secretKey)
        COSCredentials cred = new BasicCOSCredentials(ACCESSKEY, SECRETKEY);
        // 2 设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
        // clientConfig中包含了设置region, https(默认http), 超时, 代理等set方法, 使用可参见源码或者接口文档FAQ中说明
        ClientConfig clientConfig = new ClientConfig(new Region(REGIONID));
        // 3 生成cos客户端
        COSClient cosClient = new COSClient(cred, clientConfig);

Java代码(在main函数里可以测试,不过都被我注释掉了)

/**
 * @Author: SunJunxian
 * @Date: 2018/12/17
 * @De ion: java实现腾讯云存储服务(COSClient)
 * @REGIONID 区域
 * @KEY  上传上云之后的名字
 * @KEY01 需要删除的文件
 */
public class CosClientTest {

    private static final String ACCESSKEY = \"XXXXXX\";
    private static final String SECRETKEY = \"XXXXXX\";
    private static final String BUCKETNAME = \"XXXXXX-12517827811\";
    private static final String APPID = \"12517827811\";
    private static final String REGIONID = \"ap-guangzhou\";
    private static final String KEY=\"MyFile1/zookeeper-3.4.8.tar.gz\";
    private static final String KEY01=\"MyFile1/1.jpg\";
    /**
     * 初始化CosClient相关配置, appid、accessKey、secretKey、region
     * @return
     */
    public static COSClient getCosClient() {
        // 1 初始化用户身份信息(secretId, secretKey)
        COSCredentials cred = new BasicCOSCredentials(ACCESSKEY, SECRETKEY);
        // 2 设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
        // clientConfig中包含了设置region, https(默认http), 超时, 代理等set方法, 使用可参见源码或者接口文档FAQ中说明
        ClientConfig clientConfig = new ClientConfig(new Region(REGIONID));
        // 3 生成cos客户端
        COSClient cosClient = new COSClient(cred, clientConfig);
        // bucket的命名规则为{name}-{appid} ,此处填写的存储桶名称必须为此格式
        //String bucketName = BUCKETNAME;
        return cosClient;
    }

    /**
     * 上传文件
     * @return
     * //绝对路径和相对路径都OK
     */
    public static String uploadFile() {
//        File localFile = new File(\"E:\\\\software\\\\JavaProject\\\\demo\\\\demo20\\\\src\\\\main\\\\resources\\\\1.jpg\");
        File localFile = new File(\"E:\\\\software\\\\zookeeper-3.4.8.tar.gz\");
        Put Request put Request = new Put Request(BUCKETNAME, KEY, localFile);

        // 设置存储类型, 默认是标准(Standard), 低频(standard_ia),一般为标准的
        put Request.setStorageClass(StorageClass.Standard);

        COSClient cc = getCosClient();
        try {
            Put Result put Result = cc.put (put Request);
            // put Result会返回文件的etag
            String etag = put Result.getETag();
            System.out.println(etag);
        } catch (CosServiceException e) {
            e.printStackTrace();
        } catch (CosClientException e) {
            e.printStackTrace();
        }
        // 关闭客户端
        cc.shutdown();
        return null;
    }

    /**
     * 下载文件
     * @param bucketName
     * @param key
     * @return
     */
    public static String downLoadFile(String bucketName, String key) {
        File downFile = new File(\"E:\\\\software\\\\1.jpg\");
        COSClient cc = getCosClient();
        Get Request get Request = new Get Request(bucketName, key);

          data down   = cc.get (get Request, downFile);
        cc.shutdown();
        String etag = down  .getETag();
        return etag;
    }

    /**
     * 删除文件
     * @param bucketName
     * @param key
     */
    public static void deleteFile(String bucketName, String key) {
        COSClient cc = getCosClient();
        try {
            cc.delete (bucketName, key);
        } catch (CosClientException e) {
            e.printStackTrace();
        } finally {
            cc.shutdown();
        }

    }

    /**
     * 创建桶
     * @param bucketName
     * @return
     * @throws CosClientException
     * @throws CosServiceException
     */
    public static Bucket createBucket(String bucketName) throws CosClientException, CosServiceException {
        COSClient cc = getCosClient();
        Bucket bucket = null;
        try {
            bucket = cc.createBucket(bucketName);
        } catch (CosClientException e) {
            e.printStackTrace();
        } finally {
        }
        return bucket;
    };

    /**
     * 删除桶
     * @param bucketName
     * @throws CosClientException
     * @throws CosServiceException
     */
    public void deleteBucket(String bucketName) throws CosClientException, CosServiceException {
        COSClient cc = getCosClient();
        try {
            cc.deleteBucket(bucketName);
        } catch (CosClientException e) {
            e.printStackTrace();
        } finally {
        }
    };

    /**
     * 判断桶是否存在
     * @param bucketName
     * @return
     * @throws CosClientException
     * @throws CosServiceException
     */
    public static boolean doesBucketExist(String bucketName) throws CosClientException, CosServiceException {
        COSClient cc = getCosClient();
        boolean bucketExistFlag = cc.doesBucketExist(bucketName);
        return bucketExistFlag;
    };

    /**
     * 查看桶文件
     * @param bucketName
     * @return
     * @throws CosClientException
     * @throws CosServiceException
     */
    public static  Listing list s(String bucketName) throws CosClientException, CosServiceException {
        COSClient cc = getCosClient();

        // 获取 bucket 下成员(设置 delimiter)
        List sRequest list sRequest = new List sRequest();
        list sRequest.setBucketName(bucketName);
        // 设置 list 的 prefix, 表示 list 出来的文件 key 都是以这个 prefix 开始
        list sRequest.setPrefix(\"\");
        // 设置 delimiter 为/, 即获取的是直接成员,不包含目录下的递归子成员
        list sRequest.setDelimiter(\"/\");
        // 设置 marker, (marker 由上一次 list 获取到, 或者第一次 list marker 为空)
        list sRequest.setMarker(\"\");
        // 设置最多 list 100 个成员,(如果不设置, 默认为 1000 个,最大允许一次 list 1000 个 key)
        list sRequest.setMaxKeys(100);

         Listing  Listing = cc.list s(list sRequest);
        // 获取下次 list 的 marker
        String nextMarker =  Listing.getNextMarker();
        // 判断是否已经 list 完, 如果 list 结束, 则 isTruncated 为 false, 否则为 true
        boolean isTruncated =  Listing.isTruncated();
        List<COS Summary>  Summaries =  Listing.get Summaries();
        for (COS Summary cos Summary :  Summaries) {
            // get file path
            String key = cos Summary.getKey();
            // get file length
            long fileSize = cos Summary.getSize();
            // get file etag
            String eTag = cos Summary.getETag();
            // get last modify time
            Date lastModified = cos Summary.getLastModified();
            // get file save type
            String StorageClassStr = cos Summary.getStorageClass();
        }
        return  Listing;
    }

    /**
     *查询一个 Bucket 所在的 Region。
     * @param bucketName
     * @return
     * @throws CosClientException
     * @throws CosServiceException
     */
    public static String getBucketLocation(String bucketName) throws CosClientException , CosServiceException{
       COSClient cosClient = getCosClient();
        // bucket 的命名规则为{name}-{appid} ,此处填写的存储桶名称必须为此格式
        String location = cosClient.getBucketLocation(bucketName);
        return location;
    }

    public static void main(String[] args) {
//        uploadFile();
//          downLoadFile(BUCKETNAME , KEY);
         // deleteFile(BUCKETNAME , KEY01);
//        createBucket(\"sunjunxian01-1251782781\");
        //deleteBucket();
//        doesBucketExist(\"sunjunxian01-1251782781\");
//        System.out.println(list s(BUCKETNAME));
        //System.out.println(\"BUCKETNAME的位置:\" + getBucketLocation(BUCKETNAME));
    }
}
收藏 打印