专栏名称: ImportNew
伯乐在线旗下账号,专注Java技术分享,包括Java基础技术、进阶技能、架构设计和Java技术领域动态等。
目录
相关文章推荐
芋道源码  ·  入职第一天,看了公司代码,牛马沉默了 ·  昨天  
Java编程精选  ·  雷军删文,热搜第一! ·  4 天前  
芋道源码  ·  如何实现一个合格的分布式锁 ·  2 天前  
51好读  ›  专栏  ›  ImportNew

MJDK 如何实现压缩速率的 5 倍提升?

ImportNew  · 公众号  · Java  · 2023-09-22 11:30

正文

请到「今天看啥」查看全文



2.1 Java 语言中压缩/解压缩 API 实现原理


Java 语言中,我们可以使用 JDK 原生压缩类库(java.util.zip.*)或第三方 Jar 包提供的压缩类库两种方式来实现数据压缩/解压缩,其底层原理是通过 JNI (Java Native Interface) 机制,调用 JDK 源码或第三方 Jar 包中提供的共享库函数。详细对比如下:


其中在使用方式上,两者区别可参考如下代码。

(1)JDK 原生压缩类库(zlib 压缩库)

zip 文件压缩/解压缩代码 demo(Java)

public class ZipUtil {   //压缩    public void compress(File file, File zipFile) {        byte[] buffer = new byte[1024];        try {            InputStream     input  = new FileInputStream(file);            ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile));            zipOut.putNextEntry(new ZipEntry(file.getName()));            int length = 0;            while ((length = input.read(buffer)) != -1) {                zipOut.write(buffer, 0, length);            }            input.close();            zipOut.close();        } catch (Exception e) {            e.printStackTrace();        }    }
//解压缩 public void uncompress(File file, File outFile) { byte[] buffer = new byte[1024]; try { ZipInputStream input = new ZipInputStream(new FileInputStream(file)); OutputStream output = new FileOutputStream(outFile); if (!outFile.getParentFile().exists()) { outFile.getParentFile().mkdir(); } if (!outFile.exists()) { outFile.createNewFile(); }
int length = 0; while ((length = input.read(buffer)) != -1) { output.write(buffer, 0, length); } input.close(); output.close(); } catch (Exception e) { e.printStackTrace(); } }}

gzip 文件压缩/解压缩代码 demo(Java)

public class GZipUtil {    public void compress(File file, File outFile) {        byte[] buffer = new byte[1024];        try {            InputStream      input  = new FileInputStream(file);            GZIPOutputStream gzip   = new GZIPOutputStream(new FileOutputStream(outFile));            int              length = 0;            while ((length = input.read(buffer)) != -1) {                gzip.write(buffer, 0, length);            }            input.close();            gzip.finish();            gzip.close();        } catch (Exception e) {            e.printStackTrace();        }    }






请到「今天看啥」查看全文