本文共 3826 字,大约阅读时间需要 12 分钟。
package io;import java.io.*;import java.util.zip.ZipEntry;import java.util.zip.ZipFile;import java.util.zip.ZipInputStream;import java.util.zip.ZipOutputStream;/** * ZipUtils 压缩文件帮助类 * Created by heqianqian on 2017/4/14. */public class ZipUtils { /** * 压缩单个文件 * * @param source 源文件 * @param dest 目的文件 */ public static void zipFile(File source, File dest) { InputStream inputStream = null; ZipOutputStream zipOutputStream = null; try { inputStream = new FileInputStream(source); zipOutputStream = new ZipOutputStream(new FileOutputStream(dest)); zipOutputStream.putNextEntry(new ZipEntry(source.getName())); byte b[] = new byte[1024]; while (inputStream.read(b) != -1) { zipOutputStream.write(b); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { inputStream.close(); zipOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 压缩多个文件 * * @param dir 源文件目录 * @param dest 目的文件 */ public static void zipFiles(File dir, File dest) { if (dir.isDirectory()) { zipFiles(dir.listFiles(), dest); } } /** * 压缩多个文件 * * @param files 源文件数组 * @param dest 目的文件 */ public static void zipFiles(File[] files, File dest) { InputStream inputStream = null; ZipOutputStream zipOutputStream = null; try { zipOutputStream = new ZipOutputStream(new FileOutputStream(dest)); for (File f : files) { inputStream = new FileInputStream(f); zipOutputStream.putNextEntry(new ZipEntry(f.getName())); byte b[] = new byte[1024]; while (inputStream.read(b) != -1) { zipOutputStream.write(b); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { inputStream.close(); zipOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 解压多个文件 * * @param file 待解压文件 */ public static void unzipFiles(File file) { String path = file.getParent(); File outFile = null; InputStream inputStream = null; OutputStream outputStream = null; ZipInputStream zipInputStream = null; ZipEntry entry; try { ZipFile zipFile = new ZipFile(file); zipInputStream = new ZipInputStream(new FileInputStream(file)); while ((entry = zipInputStream.getNextEntry()) != null) { outFile = new File(path + File.separator + entry.getName()); if (!outFile.getParentFile().exists()) { outFile.getParentFile().mkdir(); } if (!outFile.exists()) { outFile.createNewFile(); } inputStream = zipFile.getInputStream(entry); outputStream = new FileOutputStream(outFile); int temp = 0; while ((temp = inputStream.read()) != -1) { outputStream.write(temp); } } } catch (IOException e) { e.printStackTrace(); } finally { try { inputStream.close(); outputStream.close(); zipInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } }}
转载地址:http://ltqli.baihongyu.com/