Compress.java 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package com.iamberry.nuonuo.util;
  2. import sun.misc.BASE64Decoder;
  3. import sun.misc.BASE64Encoder;
  4. import java.io.ByteArrayInputStream;
  5. import java.io.ByteArrayOutputStream;
  6. import java.util.zip.GZIPInputStream;
  7. import java.util.zip.GZIPOutputStream;
  8. /**
  9. * 压缩
  10. * @author sdk.jss.com.cn
  11. * @version 2.0
  12. * @since jdk1.6
  13. */
  14. public class Compress {
  15. public static String compress(String str) throws Exception {
  16. if (str == null || str.length() == 0) {
  17. return "";
  18. }
  19. byte[] tArray;
  20. ByteArrayOutputStream out = new ByteArrayOutputStream();
  21. GZIPOutputStream gzip = new GZIPOutputStream(out);
  22. try {
  23. gzip.write(str.getBytes("UTF-8"));
  24. gzip.flush();
  25. } finally {
  26. gzip.close();
  27. }
  28. tArray = out.toByteArray();
  29. out.close();
  30. BASE64Encoder tBase64Encoder = new BASE64Encoder();
  31. return tBase64Encoder.encode(tArray);
  32. }
  33. public static String uncompress(String str) throws Exception {
  34. if (str == null || str.length() == 0) {
  35. return "";
  36. }
  37. BASE64Decoder tBase64Decoder = new BASE64Decoder();
  38. byte[] t = tBase64Decoder.decodeBuffer(str);
  39. ByteArrayOutputStream out = new ByteArrayOutputStream();
  40. ByteArrayInputStream in = new ByteArrayInputStream(t);
  41. GZIPInputStream gunzip = new GZIPInputStream(in);
  42. try {
  43. byte[] buffer = new byte[256];
  44. int n;
  45. while ((n = gunzip.read(buffer)) >= 0) {
  46. out.write(buffer, 0, n);
  47. }
  48. } finally {
  49. gunzip.close();
  50. }
  51. in.close();
  52. out.close();
  53. return out.toString("UTF-8");
  54. }
  55. }