GZipSerializer.java 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package com.sdyc.ndmp.protobuf.serializer;
  2. import org.apache.commons.compress.compressors.CompressorException;
  3. import org.apache.commons.compress.compressors.CompressorInputStream;
  4. import org.apache.commons.compress.compressors.CompressorOutputStream;
  5. import org.apache.commons.compress.compressors.CompressorStreamFactory;
  6. import org.apache.commons.io.IOUtils;
  7. import java.io.ByteArrayInputStream;
  8. import java.io.ByteArrayOutputStream;
  9. import java.io.IOException;
  10. /**
  11. * <pre>
  12. * Created with IntelliJ IDEA.
  13. * User: lwj
  14. * Date: 2015/2/27
  15. * Time: 10:48
  16. * To change this template use File | Settings | File Templates.
  17. * </pre>
  18. *
  19. * @author lwj
  20. */
  21. public class GZipSerializer extends CompressSerializer {
  22. public GZipSerializer() {
  23. }
  24. @Override
  25. public byte[] compress(byte[] bytes) {
  26. CompressorInputStream inputStream = null;
  27. try {
  28. inputStream = new CompressorStreamFactory().createCompressorInputStream(
  29. CompressorStreamFactory.GZIP, new ByteArrayInputStream(bytes));
  30. ByteArrayOutputStream out = new ByteArrayOutputStream();
  31. IOUtils.copy(inputStream, out);
  32. inputStream.close();
  33. return out.toByteArray();
  34. } catch (IOException e) {
  35. throw new IllegalStateException(e);
  36. } catch (CompressorException e) {
  37. throw new IllegalStateException(e);
  38. }
  39. }
  40. @Override
  41. public byte[] uncompress(byte[] bytes) {
  42. ByteArrayOutputStream out = new ByteArrayOutputStream();
  43. try {
  44. CompressorOutputStream outputStream = new CompressorStreamFactory().createCompressorOutputStream(
  45. CompressorStreamFactory.GZIP, out);
  46. IOUtils.copy(new ByteArrayInputStream(bytes), outputStream);
  47. outputStream.close();
  48. return out.toByteArray();
  49. } catch (IOException e) {
  50. throw new IllegalStateException(e);
  51. } catch (CompressorException e) {
  52. throw new IllegalStateException(e);
  53. }
  54. }
  55. }