During the file transfer process, in order to make large files more convenient and fast transmission, compression is generally used to compress the file before transferring. The Deflater and Inflater classes in the java.util.zip package in JAVA provide users with the compression function of the DEFLATE algorithm. The following is the compression and decompression implementation written by itself, and the compression file content is illustrated as an example. The specific methods involved can be viewed in the JDK API for information.
/** * * @param inputByte * Byte array to be decompressed* @return Decompressed byte array* @throws IOException */ public static byte[] uncompress(byte[] inputByte) throws IOException { int len = 0; Inflater infl = new Inflater(); infl.setInput(inputByte); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] outByte = new byte[1024]; try { while (!infl.finished()) { // Decompress and output the decompressed content to the byte output stream bos len = infl.inflate(outByte); if (len == 0) { break; } bos.write(outByte, 0, len); } infl.end(); } catch (Exception e) { // } finally { bos.close(); } return bos.toByteArray(); } /** * Compress. * * @param inputByte * Byte array to be compressed* @return Compressed data* @throws IOException */ public static byte[] compress(byte[] inputByte) throws IOException { int len = 0; Deflater defl = new Deflater(); defl.setInput(inputByte); defl.finish(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] outputByte = new byte[1024]; try { while (!defl.finished()) { // Compress and output the compressed content to the byte output stream bos len = defl.deflate(outputByte); bos.write(outputByte, 0, len); } defl.end(); } finally { bos.close(); } return bos.toByteArray(); } public static void main(String[] args) { try { FileInputStream fis = new FileInputStream("D://testdeflate.txt"); int len = fis.available(); byte[] b = new byte[len]; fis.read(b); byte[] bd = compress(b); // In order for the compressed content to be transmitted on the network, Base64 encoding String is generally used to be used to encode encodestr = Base64.encodeBase64String(bd); byte[] bi = uncompress(Base64.decodeBase64(encodestr)); FileOutputStream fos = new FileOutputStream("D://testinflate.txt"); fos.write(bi); fos.flush(); fos.close(); fis.close(); } catch (Exception e) { // } }The above deflate compression implementation method in JAVA is all the content I have shared with you. I hope you can give you a reference and I hope you can support Wulin.com more.