1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 package org.nuiton.util;
35
36 import java.io.BufferedInputStream;
37 import java.io.BufferedOutputStream;
38 import java.io.BufferedReader;
39 import java.io.ByteArrayInputStream;
40 import java.io.ByteArrayOutputStream;
41 import java.io.IOException;
42 import java.io.InputStream;
43 import java.io.Reader;
44 import java.io.StringReader;
45 import java.util.zip.GZIPInputStream;
46 import java.util.zip.GZIPOutputStream;
47
48 public class GZUtil {
49
50
51
52
53
54
55
56
57
58
59
60 public static boolean isGzipStream(InputStream inputStream) throws IOException {
61
62 inputStream.mark(2);
63
64 int b = inputStream.read();
65
66 int magic = inputStream.read() << 8 | b;
67 inputStream.reset();
68 boolean gzip = magic == GZIPInputStream.GZIP_MAGIC;
69 return gzip;
70
71 }
72
73
74
75
76
77 public static StringBuffer bytesToStringBuffer(byte[] in) {
78 try {
79 if (in == null || in.length == 0) {
80 return new StringBuffer("");
81 }
82 GZIPInputStream gz = new GZIPInputStream(new BufferedInputStream(new ByteArrayInputStream(in)));
83 StringBuffer sb = new StringBuffer();
84 int c;
85
86 while ((c = gz.read()) != -1) {
87 sb.append((char) c);
88 }
89 gz.close();
90 return sb;
91 } catch (IOException eee) {
92 throw new GZUtilException("Probleme dans la decompression", eee);
93 }
94 }
95
96
97
98
99
100 public static String bytesToString(byte[] in) {
101 return bytesToStringBuffer(in).toString();
102 }
103
104
105
106
107
108 public static byte[] stringBufferToBytes(StringBuffer elem) {
109 return stringToBytes(elem.toString());
110 }
111
112
113
114
115
116 public static byte[] stringToBytes(String elem) {
117 try {
118 ByteArrayOutputStream baos = new ByteArrayOutputStream();
119 GZIPOutputStream gz = new GZIPOutputStream(new BufferedOutputStream(baos));
120 Reader sr = new BufferedReader(new StringReader(elem));
121 int c;
122 while ((c = sr.read()) != -1) {
123 gz.write((char) c);
124 }
125 gz.close();
126
127 return baos.toByteArray();
128 } catch (IOException eee) {
129 throw new GZUtilException("Probleme dans la compression", eee);
130 }
131 }
132
133 }
134