代码:
package com.sfpay.msfs.jyd.common.util;
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.io.OutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream;
public class ZipUtils {
private static final int BUFFER_SIZE = 2 * 1024;
/** * todo * * @author Rita * @date 2019年7月17日 * @param file需要压缩的文件 * ,out压缩文件输出流 * @step * @return */ public static void toZip(File file, OutputStream out) { ZipOutputStream zos = null;
try { zos = new ZipOutputStream(out); byte[] buf = new byte[BUFFER_SIZE]; zos.putNextEntry(new ZipEntry(file.getName())); int len; FileInputStream in = new FileInputStream(file); while ((len = in.read(buf)) != -1) { zos.write(buf, 0, len); } zos.closeEntry(); in.close(); } catch (Exception e) { throw new RuntimeException("zip error from ZipUtils", e); } finally { if (zos != null) { try { zos.close(); } catch (IOException e) { e.printStackTrace(); } }
} } /** * 把Zip文件解压在文件夹目录下 * * @author Rita * @date 2019年7月18日 * @param fileInputStream 需要解压的文件;parent 解压文件存放的文件夹路径 * @step * @return */ public static void toUnzip(String file, String parent) { try { ZipInputStream zin=new ZipInputStream(new FileInputStream( file));//输入源zip路径 BufferedInputStream bin=new BufferedInputStream(zin); // String Parent="d:\\user\\80003964\\桌面\\Zip"; //输出路径(文件夹目录) File fout=null; ZipEntry entry; try { while((entry = zin.getNextEntry())!=null && !entry.isDirectory()){ fout=new File(parent,entry.getName()); if(!fout.exists()){ (new File(fout.getParent())).mkdirs(); } FileOutputStream out=new FileOutputStream(fout); BufferedOutputStream bout=new BufferedOutputStream(out); int b; while((b=bin.read())!=-1){ bout.write(b); } bout.close(); out.close(); } bin.close(); zin.close(); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } } catch (FileNotFoundException e) { throw new RuntimeException(e.getMessage(), e);
} }
}