首页 > 代码库 > JAVA-ZIP和GZIP压缩实现
JAVA-ZIP和GZIP压缩实现
1、ZIP压缩实现:
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * @description ZIP格式压缩文件 * @author guo * */ public class ZipUtils { public static void main(String[] args) { try { zipFile("D:\\4.json", "D:\\test\\4zip.zip"); } catch (Exception e) { e.printStackTrace(); } } /** * ZIP方式 对文件进行压缩 * * @param source 源文件 * @param target 目标文件 * @throws IOException */ public static void zipFile(String source, String target) throws IOException { long start = System.currentTimeMillis(); FileInputStream fin = null; FileOutputStream fout = null; fin = new FileInputStream(source); fout = new FileOutputStream(target); ZipOutputStream zipOut = new ZipOutputStream(fout); zipOut.setLevel(9); ZipEntry entry = new ZipEntry("11111"); zipOut.putNextEntry(entry); byte[] buf = new byte[1024]; try { int num; while ((num = fin.read(buf)) != -1) { zipOut.write(buf, 0, num); } } finally { if (zipOut != null) zipOut.close(); if (fout != null) fout.close(); if (fin != null) fin.close(); } System.out.println(System.currentTimeMillis() - start); } }
2、GZIP压缩实现
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.GZIPOutputStream; /** * @description GZIP格式压缩文件 * @author guo */ public class GZipUtils { public static void main(String[] args) throws IOException { zipFile("D:\\4.json", "D:\\test\\4.zip"); } /** * GZIP方式 对文件进行压缩 * * @param source 源文件 * @param target 目标文件 * @throws IOException */ public static void zipFile(String source, String target) throws IOException { long start = System.currentTimeMillis(); FileInputStream fin = null; FileOutputStream fout = null; GZIPOutputStream gzout = null; try { fin = new FileInputStream(source); fout = new FileOutputStream(target); gzout = new GZIPOutputStream(fout); byte[] buf = new byte[1024]; int num; while ((num = fin.read(buf)) != -1) { gzout.write(buf, 0, num); } } finally { if (gzout != null) gzout.close(); if (fout != null) fout.close(); if (fin != null) fin.close(); } System.out.println(System.currentTimeMillis() - start); } }
JAVA-ZIP和GZIP压缩实现
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。