java解压缩文件

2023-10-04  本文已影响0人  Yluozi

解压tar文件


    /*tar 解压缩*/
    public static FileInputStream extractTar(FileInputStream fileInputStream, String destinationFolderPath) throws IOException {
        File outputFile = File.createTempFile("temp", ".tmp");
        try (
         BufferedInputStream bis = new BufferedInputStream(fileInputStream);
         TarArchiveInputStream tarInputStream = new TarArchiveInputStream(bis)) {

            TarArchiveEntry tarEntry;
            while ((tarEntry = tarInputStream.getNextTarEntry()) != null) {
                outputFile.deleteOnExit();
                if (tarEntry.isDirectory()) {
                    outputFile.mkdirs();
                } else {
                    outputFile.getParentFile().mkdirs();
                    try (OutputStream outputStream = new FileOutputStream(outputFile)) {
                        byte[] buffer = new byte[4096];
                        int bytesRead;
                        while ((bytesRead = tarInputStream.read(buffer)) != -1) {
                            outputStream.write(buffer, 0, bytesRead);
                        }
                    }
                }
            }
            System.out.println("Tar file extraction completed.");
            return new FileInputStream(outputFile.getPath());

        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("Tar file  is  null.");
        return null;
    }

解压zip文件

import org.apache.log4j.Logger;

import java.io.*;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.zip.GZIPInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
public class Zip {
    private static final Logger logger = Logger.getLogger(Zip.class);
    private String zipfileName = null;
    private BufferedOutputStream bufferedOutputStream;



    public Zip(String fileName) {
        this.zipfileName = fileName;
    }
    /**

     * zip解压

     * @param srcFile        zip源文件

     * @param destDirPath     解压后的目标文件夹

     * @throws RuntimeException 解压失败会抛出运行时异常

     */

    public void unzipFileZipNew(File srcFile, String destDirPath) throws RuntimeException {

        long start = System.currentTimeMillis();

        // 判断源文件是否存在

        if (!srcFile.exists()) {

            throw new RuntimeException(srcFile.getPath() + "所指文件不存在");

        }

        // 开始解压

        ZipFile zipFile = null;

        try {
            zipFile = new ZipFile(srcFile);

            Enumeration<?> entries = zipFile.entries();

            while (entries.hasMoreElements()) {

                ZipEntry entry = (ZipEntry) entries.nextElement();

                logger.info("解压" + entry.getName());

                // 如果是文件夹,就创建个文件夹

                if (entry.isDirectory()) {

                    String dirPath = destDirPath + "/" + entry.getName();

                    File dir = new File(dirPath);

                    dir.mkdirs();

                } else {

                    // 如果是文件,就先创建一个文件,然后用io流把内容copy过去

                    File targetFile = new File(destDirPath + "/" + entry.getName());

                    // 保证这个文件的父文件夹必须要存在

                    if(!targetFile.getParentFile().exists()){

                        targetFile.getParentFile().mkdirs();

                    }

                    targetFile.createNewFile();

                    // 将压缩文件内容写入到这个文件中

                    InputStream is = zipFile.getInputStream(entry);

                    FileOutputStream fos = new FileOutputStream(targetFile);

                    int len;

                    byte[] buf = new byte[1024];

                    while ((len = is.read(buf)) != -1) {

                        fos.write(buf, 0, len);

                    }

                    // 关流顺序,先打开的后关闭

                    fos.close();

                    is.close();

                }

            }

            long end = System.currentTimeMillis();

            logger.info("解压完成,耗时:" + (end - start) +" ms");

        } catch (Exception e) {
            logger.info("解压失败"+e);
            throw new RuntimeException("unzip error from ZipUtils", e);

        } finally {

            if(zipFile != null){

                try {

                    zipFile.close();

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

        }

    }

}

2解压gzip文件

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;

import org.apache.commons.compress.archivers.ArchiveInputStream;
import org.apache.commons.compress.archivers.ArchiveStreamFactory;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.log4j.Logger;

public class GZip {

    private static final Logger logger = Logger.getLogger(GZip.class);
    private BufferedOutputStream bufferedOutputStream;

    private String zipfileName = null;

    public GZip(String fileName) {
        this.zipfileName = fileName;
    }



    // 解压缩tar + GZIP文件
    public void unzipFileTarzip(String outputDirectory) {
        FileInputStream fis = null;
        ArchiveInputStream in = null;
        BufferedInputStream bufferedInputStream = null;
        try {
            fis = new FileInputStream(zipfileName);
            GZIPInputStream is = new GZIPInputStream(new BufferedInputStream(fis));
            in = new ArchiveStreamFactory().createArchiveInputStream(ArchiveStreamFactory.AR, is);
            bufferedInputStream = new BufferedInputStream(in);
            TarArchiveEntry entry = (TarArchiveEntry) in.getNextEntry();
            while (entry != null) {
                String name = entry.getName();
                String[] names = name.split("/");
                String fileName = outputDirectory;
                for(int i = 0;i<names.length;i++){
                    String str = names[i];
                    fileName = fileName + File.separator + str;
                }
                if (name.endsWith("/")) {
                    FileUtil.mkFolder(fileName);
                } else {
                    File file = FileUtil.mkFile(fileName);
                    bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file));
                    int b;
                    while ((b = bufferedInputStream.read()) != -1) {
                        bufferedOutputStream.write(b);
                    }
                    bufferedOutputStream.flush();
                    bufferedOutputStream.close();
                }
                entry = (TarArchiveEntry) in.getNextEntry();
            }

        } catch (Exception e) {
            logger.info(e.getMessage(), e);
        } finally {
            try {
                if (bufferedInputStream != null) {
                    bufferedInputStream.close();
                }
            } catch (IOException e) {
                logger.info(e.getMessage(), e);
            }
        }
    }

    // 解压缩GZIP文件
    public void unzipFileGzip(String outputDirectory) {
        logger.info("unzipFileGzip 开始解压缩:");
        FileInputStream fis = null;
        FileOutputStream out = null;

        try {
            fis = new FileInputStream(zipfileName);
            GZIPInputStream in = new GZIPInputStream(new BufferedInputStream(fis));
            out = new FileOutputStream(zipfileName.substring(0, zipfileName.indexOf(".")) + ".xml");

            byte[] buf = new byte[1024];
            int len;
            while((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }

            in.close();
            out.close();
        } catch(Exception e) {
            logger.info(e.getMessage(), e);
            logger.error("zipfileName:"+zipfileName);
        }
        logger.info("解压缩完成");
    }
}

上一篇 下一篇

猜你喜欢

热点阅读