package com.dji.sample.media.util; import com.dji.sample.patches.utils.TimerUtil; import io.minio.MinioClient; import io.minio.RemoveObjectArgs; import io.minio.StatObjectArgs; import io.minio.StatObjectResponse; import io.minio.errors.MinioException; import java.io.*; import java.nio.file.*; import java.util.*; import java.util.zip.*; public class MinioFileDownloader { private final String bucketPath; public MinioFileDownloader(String bucketPath) { this.bucketPath = bucketPath; } public void downloadAndZipFolders(List prefixes, String localSaveDir,String time) throws Exception { // 创建目标文件夹路径并生成zip文件名 Path localSavePath = Paths.get(localSaveDir); if (!Files.exists(localSavePath)) { Files.createDirectories(localSavePath); } String zipFileName = localSavePath.resolve(time).toString(); // 创建压缩文件输出流 try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFileName))) { zos.setLevel(Deflater.BEST_COMPRESSION); // 使用最高压缩级别 // 遍历每个前缀 for (String prefix : prefixes) { // 从本地文件系统获取文件 String localFolderPath = bucketPath + "/" + prefix; File localFolder = new File(localFolderPath); if (!localFolder.exists() || !localFolder.isDirectory()) { throw new FileNotFoundException("Local folder not found: " + localFolderPath); } // 压缩文件夹 zipFolder(localFolder, prefix, zos); } } } private void zipFolder(File folder, String parentFolder, ZipOutputStream zos) throws IOException { for (File file : folder.listFiles()) { if (file.isDirectory()) { zipFolder(file, parentFolder + "/" + file.getName(), zos); continue; } zos.putNextEntry(new ZipEntry(parentFolder + "/" + file.getName())); try (FileInputStream fis = new FileInputStream(file)) { byte[] buffer = new byte[1024]; int length; while ((length = fis.read(buffer)) >= 0) { zos.write(buffer, 0, length); } } zos.closeEntry(); } } public static void main(String[] args) { boolean success = deleteFileFromMinio("http://139.196.74.78:9000", "sxkj", "sxkj2024", "cloud-bucket", "test/瑞金图片.jpeg"); if (!success) { System.out.println("File deletion failed or file did not exist."); } } public static boolean deleteFileFromMinio(String endpoint, String accessKey, String secretKey, String bucketName, String objectName) { try { // 创建MinioClient实例 MinioClient minioClient = MinioClient.builder() .endpoint(endpoint) .credentials(accessKey, secretKey) .build(); // 检查文件是否存在 try { StatObjectResponse stat = minioClient.statObject(StatObjectArgs.builder() .bucket(bucketName) .object(objectName) .build()); System.out.println("File exists, proceeding with deletion."); // 删除文件 minioClient.removeObject(RemoveObjectArgs.builder() .bucket(bucketName) .object(objectName) .build()); System.out.println("File deleted successfully"); return true; } catch (Exception e) { // 如果文件不存在,则捕获异常 System.out.println("File does not exist or cannot be accessed: " + e.getMessage()); return false; } } catch (Exception e) { System.out.println("Unexpected error: " + e.getMessage()); return false; } } }