Java 实现下载指定minio目录下的所有内容到本机
需要把minio中,指定目录下的所有文件保存到本机指定位置,具体实现方法如下:
1、添加依赖
确保项目中引入了 MinIO 的 Java SDK
<dependency><groupId>io.minio</groupId><artifactId>minio</artifactId><version>8.4.3</version> <!-- 请根据最新版本调整 -->
</dependency>
2、实现方法
/*** 下载 Minio Directory 到本地目录** @param bucketName 存储桶名称* @param directoryPath directory path (目录路径)* @param localDirectory 本地目录* @param minioClient Minio 客户端* @return {@link List }<{@link String }>*/public static List<String> downloadMinioDirectory(String bucketName, String directoryPath, String localDirectory, MinioClient minioClient) throws Exception {// 确保本地目录存在File localDirFile = new File(localDirectory);if (!localDirFile.exists()) {localDirFile.mkdirs();}// 获取目录下的所有对象Iterable<Result<Item>> results = minioClient.listObjects(ListObjectsArgs.builder().bucket(bucketName).prefix(directoryPath)// 递归列出目录下的所有文件.recursive(true).build());// 返回记录List<String> resInfo = new ArrayList<>();// 遍历每个对象并下载for (Result<Item> result : results) {Item item = result.get();// 对象的键名String objectName = item.objectName();String relativePath = objectName.substring(directoryPath.length()).replaceFirst("^/", "");// 构造本地文件路径Path localFilePath = Paths.get(localDirectory, relativePath);// 创建必要的父目录Files.createDirectories(localFilePath.getParent());// 下载文件到本地minioClient.downloadObject(DownloadObjectArgs.builder().bucket(bucketName).object(objectName).filename(localFilePath.toString()).build());resInfo.add(String.valueOf(localFilePath));log.info("Downloaded: {} -> {}", objectName, localFilePath);}return resInfo;}
3、接口调用
/*** 下载当前服务机器目录 (下载到本机目录)** @param bucketName 存储桶名称 minio-data* @param remotePath 远程路径 model-file-path/data/28588882828181888/* @return {@link ResponseEntity }<{@link ? }>*/@PostMapping("/downloadCatalog")public ResponseEntity<?> downloadCatalog(@RequestParam String bucketName, @RequestParam String remotePath) {try {// 初始化 MinIO 客户端MinioClient minioClient = MinioClient.builder().endpoint(minioConfig.getEndpoint()).credentials(minioConfig.getAccessKey(), minioConfig.getSecretKey()).build();// 使用 substring 和 lastIndexOf 方法提取 remotePath 中最后一级目录int lastSlashIndex = remotePath.lastIndexOf("/");int secondLastSlashIndex = remotePath.lastIndexOf("/", lastSlashIndex - 1);String lastLevelContents = remotePath.substring(secondLastSlashIndex + 1, lastSlashIndex);// 本地保存路径String localDirectoryPath = "/home/data/temp/" + lastLevelContents;// 调用下载方法List<String> result = downloadMinioDirectory(bucketName, remotePath, localDirectoryPath, minioClient);// 返回内容return ResponseEntity.ok(Map.of("code", 200,"data", result,"msg", "下载完成"));} catch (Exception e) {return ResponseEntity.status(500).body(Map.of("code", 500,"msg", "下载失败","error", e.getMessage()));}}
至此,即可实现下载minio中指定目录下的所有文件内容了。