项目中解压tar.gz

前段项目中有块时需要解压tar.gz文件的需要,我百度了好久,没有合适的。因为我需要解压后直接写入内存进行文件解析,而不是写入本地文件里。后来终于遇到对的人,提供了解决方案,以此记录。

 public static void main(String[] args) throws Exception {
	File file = new File("D:\\testFolder\\redis.tar.gz");
    FileInputStream fis = new FileInputStream(file);
    Map<String, byte[]> map = uncompressToByteArray(fis);

    FileOutputStream fout = null;
    //获取文件名称
    for (Map.Entry thisentry : map.entrySet()) {
        Object key = thisentry.getKey();

        //解析对应的文件内容 元类型是byte[]
        byte[] bytes = map.get(key);

        //写入文件  此处也可以省略
        File file2 = new File("D://testt//cc.txt");
        fout = new FileOutputStream(file2);
        fout.write(bytes);

        //将文件内容解析
        String str = new String(bytes,"utf-8");
        System.out.println("当前文件:" + key);
        System.out.println(str);
        fout.close();
    }
    System.out.println("解压后有"+map.size()+"个文件");
}


public static Map<String, byte[]> uncompressToByteArray(InputStream fis)  {
    try {
        GZIPInputStream is = new GZIPInputStream(new BufferedInputStream(fis));
        ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("tar" , is);
        Map<String, byte[]> map = new HashMap<>();
        TarArchiveEntry entry = null;
        while ( (entry = (TarArchiveEntry)in.getNextEntry() ) != null) {
            String name = entry.getName();
            if (! entry.isDirectory()) {
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                byte[] buf = new byte[1024];
                int len = -1;
                while ((len = in.read(buf, 0, buf.length)) > -1) {
                    out.write(buf, 0, len);
                }
                map.put(name, out.toByteArray());
                out.close();
            }
        }

        in.close();
        return map;
    } catch(Exception e) {
        throw new RuntimeException(e);
    }
}

以上就是完整参考。

工作四个月了,觉得自己欠缺的太多了,还是什么都不会,好多东西都得问,悟性太差啊这老铁,不过,加油~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值