首页java › java.util.zip.Deflater 压缩 inflater解压

java.util.zip.Deflater 压缩 inflater解压

  1. import java.util.zip.Deflater;
  2. import java.util.zip.Inflater;
  3. import java.util.zip.DataFormatException;
  4. import java.io.ByteArrayOutputStream;
  5. public class CompressionTools {
  6.   // Export only static methods
  7.   private CompressionTools() {}
  8.   public static byte[] compress(byte[] value, int offset, int length, int compressionLevel) {
  9.     ByteArrayOutputStream bos = new ByteArrayOutputStream(length);
  10.     Deflater compressor = new Deflater();
  11.     try {
  12.       compressor.setLevel(compressionLevel);  //将当前压缩级别设置为指定值。
  13.       compressor.setInput(value, offset, length);
  14.       compressor.finish(); //调用时,指示压缩应当以输入缓冲区的当前内容结尾。
  15.       // Compress the data
  16.       final byte[] buf = new byte[1024];
  17.       while (!compressor.finished()) {
  18.     //如果已到达压缩数据输出流的结尾,则返回 true。
  19.         int count = compressor.deflate(buf);
  20.          // 使用压缩数据填充指定缓冲区。
  21.         bos.write(buf, 0, count);
  22.       }
  23.     } finally {
  24.       compressor.end(); //关闭解压缩器并放弃所有未处理的输入。
  25.     }
  26.     return bos.toByteArray();
  27.   }
  28.   public static byte[] compress(byte[] value, int offset, int length) {
  29.     return compress(value, offset, length, Deflater.BEST_COMPRESSION);
  30.   // 最佳压缩的压缩级别
  31.   }
  32.    public static byte[] compress(byte[] value) {
  33.     return compress(value, 0, value.length, Deflater.BEST_COMPRESSION);
  34.   }
  35.    public static byte[] decompress(byte[] value) throws DataFormatException {
  36.     ByteArrayOutputStream bos = new ByteArrayOutputStream(value.length);
  37.     Inflater decompressor = new Inflater();
  38.     try {
  39.       decompressor.setInput(value);
  40.       final byte[] buf = new byte[1024];
  41.       while (!decompressor.finished()) {
  42.         int count = decompressor.inflate(buf);
  43.         bos.write(buf, 0, count);
  44.       }
  45.     } finally {
  46.       decompressor.end();
  47.     }
  48.     return bos.toByteArray();
  49.   }
  50. }

发表评论

注意 - 你可以用以下 HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>