文件ZIp的对byte[]的压缩和解压缩

首先:

1、将文件转化为byte[]数组

private byte[] getBytesFromFile(File filethrows IOException {

        InputStream in = new FileInputStream(file);

        long length = file.length();

        if (length > Integer.MAX_VALUE) {

           throw new LogicException("文件过大,不能传输");

        }

       byte[] bytes = new byte[(intlength];

       int offset = 0;

       int numRead = 0;

        while (offset < bytes.length && (numRead = in.read(bytesoffsetbytes.length - offset)) >= 0) {

             offset += numRead;

        }

        if (offset < bytes.length) {

              throw new IOException("不能转换,");

         }

         in.close();

         return bytes;

}

a) 压缩:

public byte[] zip(byte[] data) {

      byte[] b = null;

      try {

           ByteArrayOutputStream bos = new ByteArrayOutputStream();

           ZipOutputStream zip = new ZipOutputStream(bos);

          ZipEntry entry = new ZipEntry("~~~1.bmp");

          entry.setSize(data.length);//返回条目数据的未压缩大小;如果未知,则返回 -1。

          zip.putNextEntry(entry);// 开始写入新的 ZIP 文件条目并将流定位到条目数据的开始处

          zip.write(data);//将字节数组写入当前 ZIP 条目数据。

         zip.closeEntry();

         zip.close();

         b = bos.toByteArray();

   } catch (Exception ex) {

         ex.printStackTrace();

    }

return b;

}


 

b) 解压缩:

public byte[] unZip(byte[] data) {

        byte[] b = null;

         try {

           ByteArrayInputStream bis = new ByteArrayInputStream(data);

             ZipInputStream zip = new ZipInputStream(bis);

           while (zip.getNextEntry() != null) {

           byte[] buf = new byte[1024];

           int num = -1;

           ByteArrayOutputStream baos = new ByteArrayOutputStream();

           while ((num = zip.read(buf, 0, buf.length)) != -1) {

                  baos.write(buf, 0, num);

           }

           b = baos.toByteArray();

           baos.flush();

           baos.close();

           }

           zip.close();

           bis.close();

           catch (Exception ex) {

                   ex.printStackTrace();

           }

           return b;

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值