JAVA中的deflate压缩实现方法

网友投稿 300 2023-07-07


JAVA中的deflate压缩实现方法

在文件的传输过程中,为了使大文件能够更加方便快速的传输,一般采用压缩的办法来对文件压缩xDErIZd后再传输,java中的java.utilhttp://.zip包中的Deflater和Inflater类为使用者提供了DEFLATE算法的压缩功能,以下是自已编写的压缩和解压缩实现,并以压缩文件内容为例说明,其中涉及的具体方法可查看JDK的API了解说明。

/**

*

* @param inputByte

* 待解压缩的字节数组

* @return 解压缩后的字节数组

* @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()) {

// 解压缩并将解压缩后的内容输出到字节输出流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();

}

/**

* 压缩.

*

* @param inputByte

* 待压缩的字节数组

* @return 压缩后的数据

* @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()) {

// 压缩并将压缩后的内容输出到字节输出流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);

// 为了压缩后的内容能够在网络上传输,一般采用Base64编码

String 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) {

//

}

}


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:springboot与mybatis整合实例详解(完美融合)
下一篇:java设计模式之适配器模式
相关文章

 发表评论

暂时没有评论,来抢沙发吧~