|
| 1 | +package com.qiniu.android.utils; |
| 2 | + |
| 3 | +import java.io.ByteArrayInputStream; |
| 4 | +import java.io.ByteArrayOutputStream; |
| 5 | +import java.io.File; |
| 6 | +import java.io.IOException; |
| 7 | +import java.io.RandomAccessFile; |
| 8 | +import java.util.zip.GZIPInputStream; |
| 9 | +import java.util.zip.GZIPOutputStream; |
| 10 | + |
| 11 | +public class GZipUtil { |
| 12 | + |
| 13 | + public static byte[] gZip(String string){ |
| 14 | + if (string == null){ |
| 15 | + return null; |
| 16 | + } |
| 17 | + return gZip(string.getBytes()); |
| 18 | + } |
| 19 | + |
| 20 | + public static byte[] gZip(byte[] bytes){ |
| 21 | + if (bytes == null){ |
| 22 | + return null; |
| 23 | + } |
| 24 | + if (bytes.length == 0){ |
| 25 | + return bytes; |
| 26 | + } |
| 27 | + |
| 28 | + ByteArrayOutputStream out = new ByteArrayOutputStream(); |
| 29 | + GZIPOutputStream gzip = null; |
| 30 | + try { |
| 31 | + gzip = new GZIPOutputStream(out); |
| 32 | + gzip.write(bytes); |
| 33 | + } catch (IOException e){ |
| 34 | + } finally { |
| 35 | + if (gzip != null){ |
| 36 | + try { |
| 37 | + gzip.close(); |
| 38 | + } catch (IOException e){ |
| 39 | + } |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + return out.toByteArray(); |
| 44 | + } |
| 45 | + |
| 46 | + public static byte[] gUnzip(byte[] bytes) { |
| 47 | + if (bytes == null){ |
| 48 | + return null; |
| 49 | + } |
| 50 | + if (bytes.length == 0){ |
| 51 | + return bytes; |
| 52 | + } |
| 53 | + |
| 54 | + ByteArrayOutputStream out = new ByteArrayOutputStream(); |
| 55 | + ByteArrayInputStream in = new ByteArrayInputStream(bytes); |
| 56 | + |
| 57 | + GZIPInputStream gunzip = null; |
| 58 | + try { |
| 59 | + gunzip = new GZIPInputStream(in); |
| 60 | + byte[] buffer = new byte[256]; |
| 61 | + int n; |
| 62 | + while ((n = gunzip.read(buffer)) >= 0) { |
| 63 | + out.write(buffer, 0, n); |
| 64 | + } |
| 65 | + } catch (IOException e) { |
| 66 | + } finally { |
| 67 | + if (gunzip != null) { |
| 68 | + try { |
| 69 | + gunzip.close(); |
| 70 | + } catch (IOException e) { |
| 71 | + } |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + return out.toByteArray(); |
| 76 | + } |
| 77 | +} |
0 commit comments