/** * 批量下载 * 参数一:目标地址(OSS)注意:是桶名后面的路径,第一个文件名前没有(/)斜杠 * 参数二:本地地址(本地服务器) * @param prefix * @param directoryPath * @return * @throws IOException */ public static boolean listFiles(String prefix, String directoryPath) throws IOException { // Endpoint以杭州为例,其它Region请按实际情况填写。 String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录RAM控制台创建RAM账号。 String accessKeyId = "LTAI4FxDyPQuHxZsbRZUjmSg"; String accessKeySecret = "BLvnbPliIyivXeUQxcyJMZUydJEoRO"; String bucketName = "ty-archives"; // 创建OSSClient实例。 OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); boolean flag; String marker = ""; do { ListObjectsRequest lor = new ListObjectsRequest(); //指定目录 lor.setPrefix(prefix); lor.setBucketName(bucketName); // 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(bucketName, 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(); return true; }