支持有空文件夹
// 打包String url = dir0 + File.separator + dir1;log.info("将此文件夹打成zip包:"+url);String urlZip = dir0 + File.separator + dir1 + ".zip";File file = new File(url);// 方法2:压缩包内支持空文件夹ZipUtil.zip(FileUtil.file(urlZip), true, file.listFiles());
踩坑,不知道问什么不支持,反正没实现
/*** 打压缩包*/public static void compress(String fromPath, String toPath) throws Exception {File fromFile = new File(fromPath);File toFile = new File(toPath);if (!fromFile.exists()) {throw new DbptException(fromPath + "不存在!");}try (FileOutputStream outputStream = new FileOutputStream(toFile); CheckedOutputStream checkedOutputStream = new CheckedOutputStream(outputStream, new CRC32()); ZipOutputStream zipOutputStream = new ZipOutputStream(checkedOutputStream)) {//区分重载方法,无实际意义String baseDir = "";//进行一次循环为了去除最外层文件夹File[] files = fromFile.listFiles();// ZipUtil.zip(toFile, true, files);for (File file : files) {compress(file, zipOutputStream, baseDir);}}}private static void compress(File file, ZipOutputStream zipOut, String baseDir) throws IOException {if (file.isDirectory()) {compressDirectory(file, zipOut, baseDir);} else {compressFile(file, zipOut, baseDir);}}private static void compressFile(File file, ZipOutputStream zipOut, String baseDir) throws IOException {if (!file.exists()) {return;}try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {System.out.println("baseDir + file.getName() = " + baseDir + file.getName());ZipEntry entry = new ZipEntry(baseDir + file.getName());zipOut.putNextEntry(entry);int count;byte[] data = new byte[1024];while ((count = bis.read(data, 0, 1024)) != -1) {zipOut.write(data, 0, count);}}}private static void compressDirectory(File dir, ZipOutputStream zipOut, String baseDir) throws IOException {System.out.println("dir.getName() = " + baseDir + File.separator + dir.getName() + File.separator);ZipEntry entry = new ZipEntry(baseDir + File.separator + dir.getName() + File.separator);zipOut.putNextEntry(entry);File[] files = dir.listFiles();if (files != null && ArrayUtils.isNotEmpty(files)) {for (File file : files) {compress(file, zipOut, baseDir + dir.getName() + File.separator);}}}