zip-压缩,只依赖J2ME

来源:互联网 发布:u盘什么牌子好 知乎 编辑:程序博客网 时间:2024/06/09 15:13
直接上代码:
import java.io.ByteArrayOutputStream;import java.io.InputStream;import java.io.OutputStream;import java.util.zip.Deflater;import java.util.zip.DeflaterOutputStream;import java.util.zip.Inflater;import java.util.zip.InflaterInputStream;/** * 只依赖J2ME API,目前一共有4个方法,压缩成zip包的方法还没有实现。 * //会多出8个byte的header,以此来判断压缩算法等,可以通过下面的语句来验证: * System.out.println(ZipUtil.compress( "".getBytes() ).length); * @author river.wang */public class ZipUtil {public static byte[] compress(byte[] data) throws Exception{Deflater compresser = new Deflater();compresser.setInput(data);compresser.finish();ByteArrayOutputStream bos = new ByteArrayOutputStream();byte[] buf = new byte[1024];while (!compresser.finished()) {    int i = compresser.deflate(buf);    //把buf写入到bos中,流的写是写入流自己,流的读是从流中读。    bos.write(buf, 0, i);}compresser.end();return bos.toByteArray();}public static byte[] decompress(byte[] data) throws Exception{Inflater decompresser = new Inflater();decompresser.setInput(data);ByteArrayOutputStream bos = new ByteArrayOutputStream();byte[] buf = new byte[1024];while (!decompresser.finished()) {    int i = decompresser.inflate(buf);    bos.write(buf, 0, i);}decompresser.end();return bos.toByteArray();}/** * 压缩data,并写向os,如果os是FileOutputStream的话,并不能打成zip包,其他的没有试 * 只是把压缩的data写入os流,以文本的形式存在 */public static void compress(byte[] data, OutputStream os) throws Exception{    DeflaterOutputStream dos = new DeflaterOutputStream(os);    dos.write(data, 0, data.length);    dos.finish();    dos.flush();}public static byte[] decompress(InputStream is) throws Exception{InflaterInputStream iis = new InflaterInputStream(is);ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);int i = 1024;byte[] buf = new byte[i];while ((i = iis.read(buf, 0, i)) > 0) {    bos.write(buf, 0, i);}return bos.toByteArray();}}
 
原创粉丝点击