JAVA中的deflate压缩实现方法
在文件的传输过程中,为了使大文件能够更加方便快速的传输,一般采用压缩的办法来对文件压缩后再传输,JAVA中的java.util.zip包中的Deflater和Inflater类为使用者提供了DEFLATE算法的压缩功能,以下是自已编写的压缩和解压缩实现,并以压缩文件内容为例说明,其中涉及的具体方法可查看JDK的API了解说明。
/** * *@paraminputByte *待解压缩的字节数组 *@return解压缩后的字节数组 *@throwsIOException */ publicstaticbyte[]uncompress(byte[]inputByte)throwsIOException{ intlen=0; Inflaterinfl=newInflater(); infl.setInput(inputByte); ByteArrayOutputStreambos=newByteArrayOutputStream(); byte[]outByte=newbyte[1024]; try{ while(!infl.finished()){ //解压缩并将解压缩后的内容输出到字节输出流bos中 len=infl.inflate(outByte); if(len==0){ break; } bos.write(outByte,0,len); } infl.end(); }catch(Exceptione){ // }finally{ bos.close(); } returnbos.toByteArray(); } /** *压缩. * *@paraminputByte *待压缩的字节数组 *@return压缩后的数据 *@throwsIOException */ publicstaticbyte[]compress(byte[]inputByte)throwsIOException{ intlen=0; Deflaterdefl=newDeflater(); defl.setInput(inputByte); defl.finish(); ByteArrayOutputStreambos=newByteArrayOutputStream(); byte[]outputByte=newbyte[1024]; try{ while(!defl.finished()){ //压缩并将压缩后的内容输出到字节输出流bos中 len=defl.deflate(outputByte); bos.write(outputByte,0,len); } defl.end(); }finally{ bos.close(); } returnbos.toByteArray(); } publicstaticvoidmain(String[]args){ try{ FileInputStreamfis=newFileInputStream("D:\\testdeflate.txt"); intlen=fis.available(); byte[]b=newbyte[len]; fis.read(b); byte[]bd=compress(b); //为了压缩后的内容能够在网络上传输,一般采用Base64编码 Stringencodestr=Base64.encodeBase64String(bd); byte[]bi=uncompress(Base64.decodeBase64(encodestr)); FileOutputStreamfos=newFileOutputStream("D:\\testinflate.txt"); fos.write(bi); fos.flush(); fos.close(); fis.close(); }catch(Exceptione){ // } }
以上这篇JAVA中的deflate压缩实现方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。