import java.util.zip.Deflater;
import java.util.zip.Inflater;
import java.util.zip.DataFormatException;
import java.io.ByteArrayOutputStream;
public class CompressionTools {
// Export only static methods
private CompressionTools() {}
public static byte[] compress(byte[] value, int offset, int length, int compressionLevel) {
ByteArrayOutputStream bos = new ByteArrayOutputStream(length);
Deflater compressor = new Deflater();
try {
compressor.setLevel(compressionLevel); //将当前压缩级别设置为指定值。
compressor.setInput(value, offset, length);
compressor.finish(); //调用时,指示压缩应当以输入缓冲区的当前内容结尾。
// Compress the data
final byte[] buf = new byte[1024];
while (!compressor.finished()) {
//如果已到达压缩数据输出流的结尾,则返回 true。
int count = compressor.deflate(buf);
// 使用压缩数据填充指定缓冲区。
bos.write(buf, 0, count);
}
} finally {
compressor.end(); //关闭解压缩器并放弃所有未处理的输入。
}
return bos.toByteArray();
}
public static byte[] compress(byte[] value, int offset, int length) {
return compress(value, offset, length, Deflater.BEST_COMPRESSION);
// 最佳压缩的压缩级别
}
public static byte[] compress(byte[] value) {
return compress(value, 0, value.length, Deflater.BEST_COMPRESSION);
}
public static byte[] decompress(byte[] value) throws DataFormatException {
ByteArrayOutputStream bos = new ByteArrayOutputStream(value.length);
Inflater decompressor = new Inflater();
try {
decompressor.setInput(value);
final byte[] buf = new byte[1024];
while (!decompressor.finished()) {
int count = decompressor.inflate(buf);
bos.write(buf, 0, count);
}
} finally {
decompressor.end();
}
return bos.toByteArray();
}
}
具体 API 地址:
http://www.gznc.edu.cn/yxsz/jjglxy/book/Java_api/java/util/zip/Deflater.html
分享到:
相关推荐
本文通过对数据压缩算法的简要介绍,然后以详细的示例演示了利用java.util.zip包实现数据的压缩与解压,并扩展到在网络传输方面如何应用java.util.zip包现数据压缩与解压
Java解压缩文件,并以ZIP格式压缩文件,主要是使用java.util.zip 包中的类来实现解压、压缩文件功能,如果你对这个类并不太熟悉,你正好可以参考一下这个类是如何用的。
Exception in thread “main“ java.util.InputMismatchException
1. java.util.concurrent - Java 并发工具包 2. 阻塞队列 BlockingQueue 3. 数组阻塞队列 ArrayBlockingQueue 4. 延迟队列 DelayQueue 5. 链阻塞队列 LinkedBlockingQueue 6. 具有优先级的阻塞队列 ...
java.util.ConcurrentModificationException 异常问题详解1
详细介绍了java.util.logging.Logger的用法和结构,对如果扩展Logger起到抛砖引玉的作用!尊重劳动成果,亲下载了要给个评价!
Tomcat内存溢出的解决方法(java.util.concurrent.ExecutionException:java.lang.OutOfMemoryError),内附解决方案!
java.util.Date与java.sql.Date互转及字符串转换为日期时间格式.docx
java.util.concurrent系列文章(1) java.util.concurrent系列文章(1) java.util.concurrent系列文章(1) java.util.concurrent系列文章(1)
Java完成zip压缩源码,包括修改后的java.util.zip下的文件(可以解决中文文件名的问题)
java 支持 中文 源程序,根据java.util.zip源码修改 java.util.zip不支持中文
java并发工具包 java.util.concurrent中文版-带书签版
详细介绍java.util.Date和java.sql.Date相互转换的多种方法总结,希望对大家有帮助
这是我在编写struts2中遇到的问题,整理出来,包括截图,希望可以帮到大家
主要给大家介绍了关于tomcat启动报:java.util.zip.ZipException错误的解决方法,文中通过示例代码介绍的非常详细,同样遇到这个问题的朋友可以参考借鉴,下面随着小编来一起学习学习吧
java.util包
世界范围内的时区列表。由 java.util.TimeZone 类导出
java.util包源码,pdf版,方便打印
使用java.util.timer实现的简单定时任务,在实现简单一次性定时任务时,使用java.util.timer非常的简单易用,适合没有接触过quartz的新手急用。