1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
| package cn.happyjava.utils;
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream;
public class ZipUtils {
public static void zipDir(String sourceDir, String targetFile, boolean overlayFile) throws IOException { if (sourceDir == null || targetFile == null) { throw new NullPointerException(); } File dir = new File(sourceDir); if (!dir.exists()) { throw new IllegalArgumentException(String.format("sourceDir[%s] not exist", sourceDir)); } if (!dir.isDirectory()) { throw new IllegalArgumentException(String.format("sourceDir[%s] is not a directory", sourceDir)); } if (!overlayFile && new File(targetFile).exists()) { throw new IllegalArgumentException(String.format("targetFile[%s] is exist,zip fail", targetFile)); } File[] files = dir.listFiles(); zip(targetFile, files); }
public static void zipFile(String targetFile, boolean overlayFile, File... files) throws IOException { if (targetFile == null) { throw new NullPointerException(); } if (!overlayFile && new File(targetFile).exists()) { throw new IllegalArgumentException(String.format("targetFile[%s] is exist,zip fail", targetFile)); } zip(targetFile, files); }
private static void zip(String targetFile, File[] files) throws IOException { if (files == null) { files = new File[0]; } try (FileOutputStream fileOutputStream = new FileOutputStream(targetFile); ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream)) { for (File file : files) { if (!file.exists()) { continue; } try (FileInputStream inputStream = new FileInputStream(file)) { ZipEntry zipEntry = new ZipEntry(file.getName()); zipOutputStream.putNextEntry(zipEntry); byte[] bytes = new byte[1024]; int length; while ((length = inputStream.read(bytes)) >= 0) { zipOutputStream.write(bytes, 0, length); } }
} } }
}
|