java鬼混笔记:压缩文件生成zip

来源:互联网 发布:托福听力软件推荐 编辑:程序博客网 时间:2024/06/05 11:08

个人学习笔记

package com.yin.test;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.util.zip.ZipEntry;import java.util.zip.ZipOutputStream;public class Test {public static void main(String[] args) throws Exception {//zipSingle();zipAll();}// 压缩单个文件public static void zipSingle() throws Exception{// 目标压缩D:盘下test.docx// 要生成的zip文件 我这命名为:testDocx.zip 在D:盘下File zipFile = new File("D:"+File.separator+ "testDocx.zip");// zip输出流ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));// buffer缓存byte[] bufs = new byte[1024];// 一个压缩文件实体 装的是D:盘下的test.docxZipEntry zipEntry = new ZipEntry("test.docx");// 这时testDocx.zip包下面有个test.docx的意思zos.putNextEntry(zipEntry);// 加入输出流BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File("D:"+File.separator+"test.docx")),1024 * 10);int read = 0;while ((read = bis.read(bufs)) != -1) {zos.write(bufs, 0, read);}bis.close();zos.close();//new File("D:"+File.separator+"test.docx").delete();// 删除原文件}// 压缩多个文件public static void zipAll(){// 假设D:盘下有  ywj文件夹, ywj文件下有N个docx文件 , 一次性打包这些文件 代码和单个一样,只是多了个循环String path = "D:"+File.separator+"ywj";File sourceFile = new File(path);if (sourceFile.exists() == false) {} else {try {File zipFile = new File("D:"+File.separator+"ywj"+File.separator+ "/ywj.zip");File[] sourceFiles = sourceFile.listFiles();if (null == sourceFiles || sourceFiles.length < 1) {} else {ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));byte[] bufs = new byte[1024 * 10];for (int i = 0; i < sourceFiles.length; i++) {ZipEntry zipEntry = new ZipEntry(sourceFiles[i].getName());zos.putNextEntry(zipEntry);BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourceFiles[i]),1024);int read = 0;while ((read = bis.read(bufs)) != -1) {zos.write(bufs, 0, read);}if (null != bis){bis.close();// 删除原文件//sourceFiles[i].delete();}}if (null != zos){zos.close();}}} catch (FileNotFoundException e) {e.printStackTrace();throw new RuntimeException(e);} catch (IOException e) {e.printStackTrace();throw new RuntimeException(e);}}}}