Created
September 20, 2019 15:41
-
-
Save dynoChris/daadd54abcc16f15bd458ad1b125abfb to your computer and use it in GitHub Desktop.
How to gzip string in java. How to compress string to byte array.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| private byte[] compress(String data) throws IOException { | |
| ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length()); | |
| GZIPOutputStream gzip = new GZIPOutputStream(bos); | |
| gzip.write(data.getBytes()); | |
| gzip.close(); | |
| byte[] compressed = bos.toByteArray(); | |
| bos.close(); | |
| return compressed; | |
| } | |
| private String decompress(byte[] compressed) throws IOException { | |
| ByteArrayInputStream bis; | |
| bis = new ByteArrayInputStream(compressed); | |
| GZIPInputStream gis; | |
| gis = new GZIPInputStream(bis); | |
| BufferedReader br; | |
| br = new BufferedReader(new InputStreamReader(gis, "UTF-8")); | |
| StringBuilder sb; | |
| sb = new StringBuilder(); | |
| String line; | |
| while ((line = br.readLine()) != null) { | |
| sb.append(line); | |
| } | |
| br.close(); | |
| gis.close(); | |
| bis.close(); | |
| return sb.toString(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment