您的位置:首页 > 其它

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

2015-07-22 20:42 381 查看
最近在做一个邮件系统,因为要和原来系统兼容,原系统是吧上传的附件进行zip压缩,然后按照32k分段存储,查询了API和相关资料,整理出文件的zip的压缩和解压缩方法,代码如下:

首先:

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

private byte[] getBytesFromFile(File file) throws IOException {

        InputStream in = new FileInputStream(file);

        long length = file.length();

        if (length > Integer.MAX_VALUE) {

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

        }

       byte[] bytes = new byte[(int) length];

       int offset = 0;

       int numRead = 0;

        while (offset < bytes.length
&& (numRead = in.read(bytes, offset, bytes.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
c135
);

          
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;

}

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息