Java实现文件压缩 使用GZIP和Zip方式

package com.lss.common.file.zip;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
/**
 * @description 压缩文件
 * @author SHOUSHEN LUAN
 * @DATE 2012-1-8下午03:10:01
 */
public class GZipUtils {
 public static void main(String[] args) throws IOException {
  zipFile("D:\\test\\kevin.mp4", "D:\\test\\kevin.mp4.zip");
  unZipFile("D:\\test\\kevin.mp4.zip", "D:\\test\\kevin.mp4.zip.mp4");
  
 }

 /**
  * Member cache 文件解压处理
  * 
  * @param buf
  * @return
  * @throws IOException
  */
 public static byte[] unGzip(byte[] buf) throws IOException {
  GZIPInputStream gzi = null;
  ByteArrayOutputStream bos = null;
  try {
   gzi = new GZIPInputStream(new ByteArrayInputStream(buf));
   bos = new ByteArrayOutputStream(buf.length);
   int count = 0;
   byte[] tmp = new byte[2048];
   while ((count = gzi.read(tmp)) != -1) {
    bos.write(tmp, 0, count);
   }
   buf = bos.toByteArray();
  } finally {
   if (bos != null) {
    bos.flush();
    bos.close();
   }
   if (gzi != null)
    gzi.close();
  }
  return buf;
 }

 /**
  * Member cache 文件压缩处理
  * 
  * @param val
  * @return
  * @throws IOException
  */
 public static byte[] gzip(byte[] val) throws IOException {
  ByteArrayOutputStream bos = new ByteArrayOutputStream(val.length);
  GZIPOutputStream gos = null;
  try {
   gos = new GZIPOutputStream(bos);
   gos.write(val, 0, val.length);
   gos.finish();
   gos.flush();
   bos.flush();
   val = bos.toByteArray();
  } finally {
   if (gos != null)
    gos.close();
   if (bos != null)
    bos.close();
  }
  return val;
 }

 /**
  * 对文件进行压缩
  * 
  * @param source
  *            源文件
  * @param target
  *            目标文件
  * @throws IOException
  */
 public static void zipFile(String source, String target) throws IOException {
  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();
  }
 }

 /**
  * 解压文件
  * 
  * @param source源文件
  * @param target目标文件
  * @throws IOException
  */
 public static void unZipFile(String source, String target)
   throws IOException {
  FileInputStream fin = null;
  GZIPInputStream gzin = null;
  FileOutputStream fout = null;
  try {
   fin = new FileInputStream(source);
   gzin = new GZIPInputStream(fin);
   fout = new FileOutputStream(target);
   byte[] buf = new byte[1024];
   int num;
   while ((num = gzin.read(buf, 0, buf.length)) != -1) {
    fout.write(buf, 0, num);
   }
  } finally {
   if (fout != null)
    fout.close();
   if (gzin != null)
    gzin.close();
   if (fin != null)
    fin.close();
  }
 }
}

 

package com.lss.common.file.zip;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

@SuppressWarnings("unchecked")
public class ZipToFile {

 public static final String ZIP_FILENAME = "D:\\test\\source.zip";// 需要解压缩的文件名
 public static final String ZIP_DIR = "D:\\test\\source\\";// 需要压缩的文件夹
 public static final String UN_ZIP_DIR = "D:\\test\\";// 要解压的文件目录
 public static final int BUFFER = 1024;// 缓存大小

 public static void main(String[] args) {
  try {
   // zipFile(ZIP_DIR,ZIP_FILENAME);
   unZipFile();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 /**
  * zip压缩功能. 压缩baseDir(文件夹目录)下所有文件,包括子目录
  * 
  * @throws Exception
  */
 public static void zipFile(String baseDir, String fileName)
   throws Exception {
  List fileList = getSubFiles(new File(baseDir));
  ZipOutputStream zos = new ZipOutputStream(
    new FileOutputStream(fileName));
  ZipEntry ze = null;
  byte[] buf = new byte[BUFFER];
  int readLen = 0;
  for (int i = 0; i < fileList.size(); i++) {
   File f = (File) fileList.get(i);
   ze = new ZipEntry(getAbsFileName(baseDir, f));
   ze.setSize(f.length());
   ze.setTime(f.lastModified());
   zos.putNextEntry(ze);
   InputStream is = new BufferedInputStream(new FileInputStream(f));
   while ((readLen = is.read(buf, 0, BUFFER)) != -1) {
    zos.write(buf, 0, readLen);
   }
   is.close();
  }
  zos.close();
 }

 /**
  * 给定根目录,返回另一个文件名的相对路径,用于zip文件中的路径.
  * 
  * @param baseDir
  *            java.lang.String 根目录
  * @param realFileName
  *            java.io.File 实际的文件名
  * @return 相对文件名
  */
 private static String getAbsFileName(String baseDir, File realFileName) {
  File real = realFileName;
  File base = new File(baseDir);
  String ret = real.getName();
  while (true) {
   real = real.getParentFile();
   if (real == null)
    break;
   if (real.equals(base))
    break;
   else
    ret = real.getName() + "/" + ret;
  }
  return ret;
 }

 /**
  * 取得指定目录下的所有文件列表,包括子目录.
  * 
  * @param baseDir
  *            File 指定的目录
  * @return 包含java.io.File的List
  */
 private static List getSubFiles(File baseDir) {
  List ret = new ArrayList();
  File[] tmp = baseDir.listFiles();
  for (int i = 0; i < tmp.length; i++) {
   if (tmp[i].isFile())
    ret.add(tmp[i]);
   if (tmp[i].isDirectory())
    ret.addAll(getSubFiles(tmp[i]));
  }
  return ret;
 }

 /**
  * 解压缩功能. 将ZIP_FILENAME文件解压到ZIP_DIR目录下.
  * 
  * @throws Exception
  */
 public static void unZipFile() throws Exception {
  ZipFile zfile = new ZipFile(ZIP_FILENAME);
  Enumeration zList = zfile.entries();
  ZipEntry ze = null;
  byte[] buf = new byte[1024];
  while (zList.hasMoreElements()) {
   ze = (ZipEntry) zList.nextElement();
   if (ze.isDirectory()) {
    File f = new File(ZIP_DIR + ze.getName());
    f.mkdir();
    continue;
   }
   OutputStream os = new BufferedOutputStream(new FileOutputStream(
     getRealFileName(ZIP_DIR, ze.getName())));
   InputStream is = new BufferedInputStream(zfile.getInputStream(ze));
   int readLen = 0;
   while ((readLen = is.read(buf, 0, 1024)) != -1) {
    os.write(buf, 0, readLen);
   }
   is.close();
   os.close();
  }
  zfile.close();
 }

 /**
  * 给定根目录,返回一个相对路径所对应的实际文件名.
  * 
  * @param baseDir
  *            指定根目录
  * @param absFileName
  *            相对路径名,来自于ZipEntry中的name
  * @return java.io.File 实际的文件
  */
 public static File getRealFileName(String baseDir, String absFileName) {
  String[] dirs = absFileName.split("/");
  File ret = new File(baseDir);
  if (dirs.length > 1) {
   for (int i = 0; i < dirs.length - 1; i++) {
    ret = new File(ret, dirs[i]);
   }
   if (!ret.exists())
    ret.mkdirs();
   ret = new File(ret, dirs[dirs.length - 1]);
   return ret;
  }
  return ret;
 }

}



 


 

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您好!感谢您的提问。 在 Java使用 pako.js 库实现 gzip压缩和解压是不可行的,因为 pako.js 是一个 JavaScript 库,无法直接在 Java使用Java实现 gzip压缩和解压有多种方法,其中常用的是使用 java.util.zip 包中的 GZIPOutputStream 和 GZIPInputStream 类来进行压缩和解压。 下面是一个示例代码,展示如何使用 GZIPOutputStream 和 GZIPInputStream 类来进行 gzip压缩和解压: ```java import java.io.*; import java.util.zip.*; public class GzipExample { public static void gzipCompress(String inputFileName, String outputFileName) throws IOException { FileInputStream fileInputStream = new FileInputStream(inputFileName); FileOutputStream fileOutputStream = new FileOutputStream(outputFileName); GZIPOutputStream gzipOutputStream = new GZIPOutputStream(fileOutputStream); byte[] buffer = new byte[1024]; int len; while ((len = fileInputStream.read(buffer)) > 0) { gzipOutputStream.write(buffer, 0, len); } gzipOutputStream.close(); fileOutputStream.close(); fileInputStream.close(); } public static void gzipDecompress(String inputFileName, String outputFileName) throws IOException { FileInputStream fileInputStream = new FileInputStream(inputFileName); GZIPInputStream gzipInputStream = new GZIPInputStream(fileInputStream); FileOutputStream fileOutputStream = new FileOutputStream(outputFileName); byte[] buffer = new byte[1024]; int len; while ((len = gzipInputStream.read(buffer)) > 0) { fileOutputStream.write(buffer, 0, len); } fileOutputStream.close(); gzipInputStream.close(); fileInputStream.close(); } public static void main(String[] args) throws IOException { String inputFileName = "input.txt"; String compressedFileName = "compressed.gz"; String decompressedFileName = "decompressed.txt"; gzipCompress(inputFileName, compressedFileName); gzipDecompress(compressedFileName, decompressedFileName); } } ``` 这段代码中,gzipCompress() 方法用于将输入文件压缩gzip 格式的输出文件gzipDecompress() 方法用于将 gzip 格式的输入文件解压为普通的文本文件。 希望这个示例能够帮助到您!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值