@Slf4j
@Component
public class FileUtils {@SneakyThrowspublic static void copyDir(File source, File target) {if (!target.exists()) {boolean mkdirs = target.mkdirs();}if (source.isDirectory()) {File[] files = source.listFiles();if (files != null) {for (File file : files) {File inFile = new File(target, file.getName());if (file.isDirectory()) {copyDir(file, inFile);} else {Files.copy(file.toPath(), inFile.toPath(), StandardCopyOption.REPLACE_EXISTING);}}}}}@SneakyThrowspublic static void removeFile(File target) {if (target.exists()) {File[] files = target.listFiles();if (files != null) {for (File file : files) {if (file.isDirectory()) {removeFile(file);} else {boolean delete = target.delete();}}}boolean delete = target.delete();}}@SneakyThrowspublic static void copyFile(File source, File target) {if (!target.exists()) {boolean newFile = target.createNewFile();}try (FileInputStream fileInputStream = new FileInputStream(source);FileOutputStream fileOutputStream = new FileOutputStream(target)) {int len;byte[] bytes = new byte[1024];while ((len = fileInputStream.read(bytes)) != -1) {fileOutputStream.write(bytes, 0, len);}fileOutputStream.flush();} catch (IOException e) {e.printStackTrace();}}public static String zipDir(File source, File target) {try {if (!target.exists()) {boolean mkdirs = target.mkdirs();}File targetFile = new File(target, source.getName() + ".zip");FileOutputStream fos = new FileOutputStream(targetFile);ZipOutputStream zipOutputStream = new ZipOutputStream(fos);zipSource(source, source.getName(), zipOutputStream);zipOutputStream.close();fos.close();return targetFile.getCanonicalPath();} catch (Exception e) {log.error("压缩文件夹失败:{}", ExceptionUtil.stacktraceToString(e));return "";}}private static void zipSource(File source, String name, ZipOutputStream zipOutputStream) throws IOException {if (source.isDirectory()) {for (File file : Objects.requireNonNull(source.listFiles())) {zipSource(file, name + "/" + file.getName(), zipOutputStream);}} else {FileInputStream fileInputStream = new FileInputStream(source);zipOutputStream.putNextEntry(new ZipEntry(name));int len;byte[] bytes = new byte[4096];while ((len = fileInputStream.read(bytes)) != -1) {zipOutputStream.write(bytes, 0, len);}zipOutputStream.closeEntry();fileInputStream.close();}}public static void main(String[] args) {File source = new File("C:\\Users\\16372\\Documents\\笔记");File target = new File("C:\\Users\\16372");String s = zipDir(source, target);System.out.println(s);}
}