Java 压缩解压(tar)

使用Apache的commons-compress-1.9.jar实现jar压缩和解压tar文件

(1)压缩文件

  private static void tarFile(File file, TarArchiveOutputStream taos) throws Exception {

        TarArchiveEntry tae = new TarArchiveEntry(file);
        tae.setSize(file.length());//大小
        tae.setName(new String(file.getName().getBytes("gbk"), "ISO-8859-1"));//不设置会默认全路径
        taos.putArchiveEntry(tae);

        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        int count;
        byte data[] = new byte[1024];
        while ((count = bis.read(data, 0, 1024)) != -1) {
            taos.write(data, 0, count);
        }
        bis.close();

        taos.closeArchiveEntry();
    }

(2)解压文件

   private static void deTarFile(String destPath, TarArchiveInputStream tais) throws Exception {

        TarArchiveEntry tae = null;
        while ((tae = tais.getNextTarEntry()) != null) {

            String dir = destPath + File.separator + tae.getName();//tar档中文件
            File dirFile = new File(dir);
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dirFile));

            int count;
            byte data[] = new byte[1024];
            while ((count = tais.read(data, 0, 1024)) != -1) {
                bos.write(data, 0, count);
            }

            bos.close();
        }
    }

测试

        //压缩
        try {
            TarArchiveOutputStream taos = new TarArchiveOutputStream(new FileOutputStream(new File("/Users/enderwang/Downloads/testTar/test.tar")));
            archiveFile(new File("/Users/enderwang/Downloads/1.txt"), taos);
            archiveFile(new File("/Users/enderwang/Downloads/2.txt"), taos);
            System.out.println("压缩成功");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        //解压
        try {
            TarArchiveInputStream tais = new TarArchiveInputStream(new FileInputStream(new File("/Users/enderwang/Downloads/testTar/test.tar")));
            dearchive("/Users/enderwang/Downloads/testTar", tais);
            tais.close();
            System.out.println("解压成功");
        } catch (Exception ex) {
            ex.printStackTrace();
        }

 

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值