Java文件压缩

从接触计算机开始,便知道了压缩文件的存在,刚开始不解(本来我一次就可以打开文件,现在却多了一步,乃是解压。。。)到了后来,我才慢慢明白压缩的重要性,除了节省空间,还节省了时间。有时候压缩文件的结果会让你吃惊,大概在原文件的50%左右,这样在网络端传输的时间将缩短一半。由此可见,它是有多么的重要。

单个文件压缩

首选GZIP

public static void compress(File source, File gzip) {
    if(source == null || gzip == null) 
        throw new NullPointerException();
    BufferedReader reader = null;
    BufferedOutputStream bos = null;
    try {
        //读取文本文件可以字符流读取
        reader = new BufferedReader(new FileReader(source));
        //对于GZIP输出流,只能使用字节流
        bos = new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream(gzip)));
        String data;
        while((data = reader.readLine()) != null) {
            bos.write(data.getBytes());
        }
    }  catch (IOException e) {
        throw new RuntimeException(e);
    }  finally {
        try {
            if(reader != null)
                reader.close();
            if(bos != null) 
                bos.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        
    }
}

多文件压缩

public static void compressMore(File[] files, File outFile) {
    if(files == null || outFile == null) 
        throw new NullPointerException();
    ZipOutputStream zipStream = null;
    try {
        //用校验流确保输出数据的完整性
        CheckedOutputStream cos = new CheckedOutputStream(new FileOutputStream(outFile), new Adler32());
        //用缓冲字节输出流进行包装
        zipStream = new ZipOutputStream(new BufferedOutputStream(cos));
        for (File file : files) {
            if(file != null) {
                BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
                try {
                    //添加实体到流中,实际上只需要指定文件名称
                    zipStream.putNextEntry(new ZipEntry(file.getName()));
                    int c;
                    while((c = in.read()) != -1)
                        zipStream.write(c);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                } finally {
                    in.close();
                }   
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        try{
            if(zipStream != null)
                zipStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • File代表文件和文件夹JDk 1.4版引入了一套新的I/O系统称之为NIONIO - Non-blocking ...
    _Raye阅读 4,308评论 0 0
  • 先不要说什么。上代码。 压缩单个文件 看完看下面的: 压缩目录下的所有文件 温馨提醒:看不清楚的可以右键保存到本地...
    Ling912阅读 3,060评论 0 0
  • 初学Linux,记录资料,以备留存,亲手测试了一部分,有的正确,不正确的也改了,没有全部测试,如有误,望大神们不吝...
    世外大帝阅读 10,890评论 1 32
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,850评论 19 139
  • 为什么要整理一下Linux下的打包和压缩工具呢?原因很简单,因为遇到问题了:游戏服务器可执行文件、配置和各种资源文...
    davidpp阅读 13,365评论 0 18

友情链接更多精彩内容