柯桥增值式服务
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

90 行
2.4KB

  1. package com.ningdatech.kqapi.common.util;
  2. import java.io.ByteArrayInputStream;
  3. import java.io.ByteArrayOutputStream;
  4. import java.io.IOException;
  5. import java.util.zip.GZIPInputStream;
  6. import java.util.zip.GZIPOutputStream;
  7. /**
  8. * <p>
  9. * 压缩为Gzip
  10. * </p>
  11. *
  12. * @author WendyYang
  13. */
  14. public class GzipUtils {
  15. /**
  16. * 使用gzip进行压缩
  17. */
  18. public static String compress(String primStr) {
  19. if (primStr == null || primStr.length() == 0) {
  20. return primStr;
  21. }
  22. ByteArrayOutputStream out = new ByteArrayOutputStream();
  23. GZIPOutputStream gzip = null;
  24. try {
  25. gzip = new GZIPOutputStream(out);
  26. gzip.write(primStr.getBytes());
  27. } catch (IOException e) {
  28. throw new RuntimeException(e);
  29. } finally {
  30. if (gzip != null) {
  31. try {
  32. gzip.close();
  33. } catch (IOException e) {
  34. throw new RuntimeException(e);
  35. }
  36. }
  37. }
  38. return new sun.misc.BASE64Encoder().encode(out.toByteArray());
  39. }
  40. /**
  41. * 使用gzip进行解压缩
  42. */
  43. public static String uncompress(String compressedStr) {
  44. if (compressedStr == null) {
  45. return null;
  46. }
  47. ByteArrayOutputStream out = new ByteArrayOutputStream();
  48. ByteArrayInputStream in = null;
  49. GZIPInputStream ginzip = null;
  50. byte[] compressed = null;
  51. String decompressed = null;
  52. try {
  53. compressed = new sun.misc.BASE64Decoder().decodeBuffer(compressedStr);
  54. in = new ByteArrayInputStream(compressed);
  55. ginzip = new GZIPInputStream(in);
  56. byte[] buffer = new byte[1024];
  57. int offset = -1;
  58. while ((offset = ginzip.read(buffer)) != -1) {
  59. out.write(buffer, 0, offset);
  60. }
  61. decompressed = out.toString();
  62. } catch (IOException e) {
  63. e.printStackTrace();
  64. } finally {
  65. if (ginzip != null) {
  66. try {
  67. ginzip.close();
  68. } catch (IOException e) {
  69. }
  70. }
  71. if (in != null) {
  72. try {
  73. in.close();
  74. } catch (IOException e) {
  75. }
  76. }
  77. try {
  78. out.close();
  79. } catch (IOException e) {
  80. }
  81. }
  82. return decompressed;
  83. }
  84. }