阿里云OSS 列出所有文件 并导出所有文件到指定目录

/**
     * 列出所有文件 并导出所有文件到指定目录
     *
     * @param prefix        oss目录
     * @param directoryPath 本地目录
     * @throws IOException 抛出io 异常
     */
    public static void listFiles(String prefix, String directoryPath) throws IOException {
        OSS ossClient = getOssClient();
        boolean flag;
        String marker = "";
        do {
            ListObjectsRequest lor = new ListObjectsRequest();
            //指定目录
            lor.setPrefix(prefix);
            lor.setBucketName(BUCKET_NAME);
            //
            lor.setMarker(marker);
            //分页大小
            lor.setMaxKeys(100);
            ObjectListing ol = ossClient.listObjects(lor);
            for (OSSObjectSummary o : ol.getObjectSummaries()) {
                System.out.println(" - " + o.getKey() + "  " + "(size = " + o.getSize() + ")");
                //
                final String path = directoryPath + o.getKey();
                //获取文件对象
                GetObjectRequest gor = new GetObjectRequest(BUCKET_NAME, o.getKey());
                //截取目录 如果目录不存在则创建
                String directoryStr = path.substring(0, path.lastIndexOf("/"));
                File directory = new File(directoryStr);
                if (!directory.exists()) {
                    directory.mkdirs();
                }
                try (//获取文件流  使用高速缓存 + 数组复制 最大效率输出文件
                     BufferedInputStream bis = new BufferedInputStream(ossClient.getObject(gor).getObjectContent());
                     BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path))) {
                    int size;
                    byte[] bytes = new byte[1024];
                    while ((size = bis.read(bytes)) != -1) {
                        bos.write(bytes, 0, size);
                    }
                    bos.flush();
                }
            }
            //当前页的最后一个文件
            marker = ol.getNextMarker();
            //是否还有文件
            flag = ol.isTruncated();

        } while (flag);

        ossClient.shutdown();
    }

    public static void main(String[] args) throws IOException {
        listFiles("ueditor/", "E:/");
    }

你可能感兴趣的:(tools,java)