在Java中提供Deflater和Inflater工具类来压缩/解压缩数据。 这两个工具类采用zlib算法,下面给出一个封装好的工具。

Java代码
  1. /**
  2. * util for compress/decompress data
  3. *
  4. * @author lichengwu
  5. * @version 1.0
  6. * @created 2013-02-07 10:14 AM
  7. */
  8. public final class CompressionUtil {
  9.  
  10. private static final int BUFFER_SIZE = 4 * 1024;
  11.  
  12. /**
  13. * compress data by {@linkplain Level}
  14. *
  15. * @author lichengwu
  16. * @created 2013-02-07
  17. *
  18. * @param data
  19. * @param level
  20. * see {@link Level}
  21. * @return
  22. * @throws IOException
  23. */
  24. public static byte[] compress(byte[] data, Level level) throws IOException {
  25.  
  26. Assert.notNull(data);
  27. Assert.notNull(level);
  28.  
  29. Deflater deflater = new Deflater();
  30. // set compression level
  31. deflater.setLevel(level.getLevel());
  32. deflater.setInput(data);
  33.  
  34. ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
  35.  
  36. deflater.finish();
  37. byte[] buffer = new byte[BUFFER_SIZE];
  38. while (!deflater.finished()) {
  39. int count = deflater.deflate(buffer); // returns the generated
  40. // code... index
  41. outputStream.write(buffer, 0, count);
  42. }
  43. byte[] output = outputStream.toByteArray();
  44. outputStream.close();
  45. return output;
  46. }
  47.  
  48. /**
  49. * decompress data
  50. *
  51. * @author lichengwu
  52. * @created 2013-02-07
  53. *
  54. * @param data
  55. * @return
  56. * @throws IOException
  57. * @throws DataFormatException
  58. */
  59. public static byte[] decompress(byte[] data) throws IOException, DataFormatException {
  60.  
  61. Assert.notNull(data);
  62.  
  63. Inflater inflater = new Inflater();
  64. inflater.setInput(data);
  65.  
  66. ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
  67. byte[] buffer = new byte[BUFFER_SIZE];
  68. while (!inflater.finished()) {
  69. int count = inflater.inflate(buffer);
  70. outputStream.write(buffer, 0, count);
  71. }
  72. byte[] output = outputStream.toByteArray();
  73. outputStream.close();
  74. return output;
  75. }
  76.  
  77. /**
  78. * Compression level
  79. */
  80. public static enum Level {
  81.  
  82. /**
  83. * Compression level for no compression.
  84. */
  85. NO_COMPRESSION(0),
  86.  
  87. /**
  88. * Compression level for fastest compression.
  89. */
  90. BEST_SPEED(1),
  91.  
  92. /**
  93. * Compression level for best compression.
  94. */
  95. BEST_COMPRESSION(9),
  96.  
  97. /**
  98. * Default compression level.
  99. */
  100. DEFAULT_COMPRESSION(-1);
  101.  
  102. private int level;
  103.  
  104. Level(
  105.  
  106. int level) {
  107. this.level = level;
  108. }
  109. public int getLevel() {
  110. return level;
  111. }
  112. }
  113. }