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 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 |
/* Compress Byte Array Using Deflater Example This Java example shows how to compress the byte array using Java Deflater class. Deflater class provides support for general purpose compression using ZLIB compression library. */ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.zip.Deflater; public class CompressByteArray { public static void main(String args[]){ String str = "aaaaaaaaaa bbbbbbbb cccccc"; //String str = "Compress byte array using Deflater example"; //get bytes byte[] bytes = str.getBytes(); /* * To create an object of Deflater, use * * Deflater() * Constructor of Deflater class. * * This will create a new compressor with * default compression level. */ Deflater deflater = new Deflater(); /* * Set the input of compressor using, * * setInput(byte[] b) * method of Deflater class. */ deflater.setInput(bytes); /* * We are done with the input, so say finish using * * void finish() * method of Deflater class. * * It ends the compression with the current contents of * the input. */ deflater.finish(); /* * At this point, we are done with the input. * Now we will have to create another byte array which can * hold the compressed bytes. */ ByteArrayOutputStream bos = new ByteArrayOutputStream(bytes.length); byte[] buffer = new byte[1024]; /* * Use * * boolean finished() * method of Deflater class to determine whether * end of compressed data output stream reached. * */ while(!deflater.finished()) { /* * use * int deflate(byte[] buffer) * method to fill the buffer with the compressed data. * * This method returns actual number of bytes compressed. */ int bytesCompressed = deflater.deflate(buffer); bos.write(buffer,0,bytesCompressed); } try { //close the output stream bos.close(); } catch(IOException ioe) { System.out.println("Error while closing the stream : " + ioe); } //get the compressed byte array from output stream byte[] compressedArray = bos.toByteArray(); System.out.println("Byte array has been compressed!"); System.out.println("Size of original array is:" + bytes.length); System.out.println("Size of compressed array is:" + compressedArray.length); } } /* Output of this program would be Byte array has been compressed! Size of original array is:26 Size of compressed array is:18 */ |
Add Comment