1/** 2 * 文件压缩 3 */ 4public class ZipFile_Compress { 5 public static void main(String[] args) throws IOException { 6 File file = new File("E:\\aaa\\web01"); 7 8 String savePath = "E:\\aaa" + File.separator + file.getName() + ".zip"; 9 File saveFile = new File(savePath); 10 if (!saveFile.getParentFile().exists()) { 11 saveFile.getParentFile().mkdirs(); 12 } 13 14 ZipOutputStream outputStream = new ZipOutputStream(new FileOutputStream(savePath, true)); 15 16 toMakeZipFilePre(file, saveFile.getParentFile().getPath(), outputStream); 17 18 outputStream.close(); 19 } 20 21 /** 22 * 文件压缩前的准备处理 23 * @param file 24 * @param savePath 25 * @param outputStream 26 * @throws IOException 27 */ 28 public static void toMakeZipFilePre(File file, String savePath, ZipOutputStream outputStream) throws IOException { 29 if (file.isDirectory()) { 30 File[] files = file.listFiles(); 31 if (files != null) { 32 for (File f : files) { 33 toMakeZipFilePre(f, savePath, outputStream); 34 } 35 } 36 } else { 37 /** 38 * 截取后面要用的文件条目 39 */ 40 String realSavePath = file.getAbsolutePath().substring(savePath.length() + 1).replaceAll("\\\\", "/"); 41 toMakeZipFile(file, realSavePath, outputStream); 42 System.out.println(realSavePath); 43 } 44 } 45 46 public static void toMakeZipFile(File file, String savePath, ZipOutputStream outputStream) throws IOException { 47 /** 48 * 将相对路径封装成条目 49 */ 50 ZipEntry zipEntry = new ZipEntry(savePath); 51 /** 52 * 在输出流中编写一条新的条目 53 */ 54 outputStream.putNextEntry(zipEntry); 55 56 InputStream inputStream = new BufferedInputStream(new FileInputStream(file)); 57 58 int len = 0; 59 byte[] bytes = new byte[1024]; 60 while ((len = inputStream.read(bytes)) != -1) { 61 outputStream.write(bytes, 0, len); 62 } 63 outputStream.flush(); 64 inputStream.close(); 65 } 66 67}
Java的文件压缩-Zip格式

红烧土豆泥
2021-03-25
1851 0 0
点赞
收藏
评论区
加载中...