项目中遇到这样的需求,特此记录ZipOutputStream的基本用法。
/**
* 将txt格式文件转换为zip格式
* @param o
* @return
* @throws Exception
*/
private byte[] txt2Zip (byte o) throws Exception {
// 1.将需要压缩的字节输出流,转为字节数组输入流,
ByteArrayInputStream bais = new ByteArrayInputStream(o);
// 2.创建字节数组输出流,用于返回压缩后的输出流字节数组
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// 3.创建压缩输出流
ZipOutputStream zipOut = new ZipOutputStream(baos);
// 进行压缩存储
zipOut.setMethod(ZipOutputStream.DEFLATED);
// 压缩级别值为0-9共10个级别(值越大,表示压缩越厉害)
zipOut.setLevel(Deflater.BEST_COMPRESSION);
//4.设置ZipEntry对象,并对需要压缩的文件命名
zipOut.putNextEntry(new ZipEntry("文件导出.txt"));
//5.读取要压缩的字节输出流,进行压缩
int temp = 0 ;
while((temp=bais.read())!=-1){
// 压缩输出
zipOut.write(temp) ;
}
bais.close();
zipOut.close();
try {
return baos.toByteArray();
} finally {
baos.close();
}
}