Java处理Zip文件

作者:曾巧(numenzq

 

    最近做的一个项目需要用Java程序读写Zip文件,迫于找不到好的工具类来处理,也只好用java.util.zip包提供的类来实现Zip文件的压缩和解压操作了,在这之前你需要了解以下几个基本概念:

  •     ZipEntryThis class is used to represent a ZIP file entry.
  •     ZipFileThis class is used to read entries from a zip file.
  •     ZipInputStreamThis class implements an input stream filter for reading files in the ZIP file format.
  •     ZipOutputStreamThis class implements an output stream filter for writing files in the ZIP file format.

 

现在我们了解一下读写Zip文件的基本流程。当解压时,从该Zip文件输入流中读取出ZipEntry,然后根据ZipEntry的信息,读取对应文件的相应字节。代码实现如下:

 

public synchronized static Map<String, byte[]> unZip(InputStream is)

           throws IOException {

 

       Map<String, byte[]> result = new HashMap<String, byte[]>();

      

       byte[] buf;

       ZipInputStream zis = new ZipInputStream(is);

       ZipEntry zipEntry = zis.getNextEntry();

 

       while (zipEntry != null) {

 

           if (zipEntry.isDirectory()) {

 

              zipEntry = zis.getNextEntry();

              continue;

           } else {

 

              buf = new byte[(int) zipEntry.getSize()];

              zis.read(buf, 0, (int) zipEntry.getSize());

               result.put(zipEntry.getName(), buf);

 

              zipEntry = zis.getNextEntry();

           }

       }

 

       return result;

}

 

压缩操作与解压操作差不多,先将文件字节流组装成ZipEntry,然后把ZipEntry加入到输出流中即可。代码实现如下:

 

public synchronized static ByteArrayOutputStream zip(Map<String, byte[]> map)

           throws IOException {

 

       ByteArrayOutputStream baos = new ByteArrayOutputStream();

       ZipOutputStream zos = new ZipOutputStream(baos);

       ZipEntry zipEntry;

 

       for (String key : map.keySet()) {

 

           zipEntry = new ZipEntry(key);

           zipEntry.setSize(map.get(key).length);

           zipEntry.setTime(System.currentTimeMillis());

 

           zos.putNextEntry(zipEntry);

           zos.write(map.get(key));

           zos.flush();

       }

       zos.close();

       return baos;

    }

   

    至此,使用上面的两个方法就能完成基本的Zip文件压缩和解压缩处理了;该方法只适合处理Zip格式的文件,对于GZip格式的文件,我相信你也能轻松搞定了:)。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值