java代码解压tar.bz2包

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java代码解压tar.bz2包相关的知识,希望对你有一定的参考价值。

package com.lxd.IO;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;

public class Demo {

    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
        decompressTarBz2(new File("E:\lxd\lxd_LXD_001.tar.bz2"), "E:\lxd\nb");
    }
    public static void decompressTarBz2(File file, String outputDir) throws IOException {
        try (TarArchiveInputStream tarIn =
                     new TarArchiveInputStream(
                             new BZip2CompressorInputStream(
                                     new FileInputStream(file)))) {
            createDirectory(outputDir, null);
            TarArchiveEntry entry;
            while ((entry = tarIn.getNextTarEntry()) != null) {
                if (entry.isDirectory()) {
                    createDirectory(outputDir, entry.getName());
                } else {
                    try (OutputStream out = new FileOutputStream(
                            new File(outputDir + File.separator + entry.getName()))) {
                        writeFile(tarIn, out);
                    }
                }
            }
        }
    }
      /**
         * 写文件
         *
         * @param in
         * @param out
         * @throws IOException
         */
        public static void writeFile(InputStream in, OutputStream out) throws IOException {
            int length;
            byte[] b = new byte[1024*100];
            while ((length = in.read(b)) != -1) {
                out.write(b, 0, length);
            }
        }
        /**
         * 创建目录
         *
         * @param outputDir
         * @param subDir
         */
        public static void createDirectory(String outputDir, String subDir) {
            File file = new File(outputDir);
            //子目录不为空
            if (!(subDir == null || subDir.trim().equals(""))) {
                file = new File(outputDir + File.separator + subDir);
            }
            if (!file.exists()) {
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                file.mkdirs();
            }
        }
}

 

以上是关于java代码解压tar.bz2包的主要内容,如果未能解决你的问题,请参考以下文章

如何只查看tar.gz压缩文件中顶层目录的列表

解压命令 tar.gz   tar.bz2

linux下解压.tar.gz .tar.bz2

打包压缩与解压功能

win主机下,怎样解压linux系统压缩的tar.gz 和 tar.bz2 格式的压缩包?

Linux tar压缩和解压