首页 > 编程语言 >JAVA解压tar、zip、rar文件

JAVA解压tar、zip、rar文件

时间:2023-07-02 16:44:32浏览次数:39  
标签:解压 JAVA tar zip return boolean File new String

1、添加pom依赖

      <!-- tar解压依赖 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-compress</artifactId>
            <version>1.20</version>
        </dependency>

        <!-- rar解压依赖 -->
        <dependency>
            <groupId>net.sf.sevenzipjbinding</groupId>
            <artifactId>sevenzipjbinding</artifactId>
            <version>16.02-2.01</version>
        </dependency>
        <dependency>
            <groupId>net.sf.sevenzipjbinding</groupId>
            <artifactId>sevenzipjbinding-all-platforms</artifactId>
            <version>16.02-2.01</version>
        </dependency>

2、具体逻辑代码

/**
     * @description:  解压tar.gz到指定的文件夹
     * @date: 2023/5/29 17:56
     * @param sourceFile  源文件绝对路径
     * @param destDir  要解压到的目录地址
     * @return boolean
     */
    public static boolean unTarGz(String sourceFile, String destDir) {
        Path source = Paths.get(sourceFile);
        Path target = Paths.get(destDir);
        boolean flag = false;
        try (InputStream fi = Files.newInputStream(source);
             BufferedInputStream bi = new BufferedInputStream(fi);
             GzipCompressorInputStream gzi = new GzipCompressorInputStream(bi);
             TarArchiveInputStream ti = new TarArchiveInputStream(gzi)) {
            ArchiveEntry entry;
            while ((entry = ti.getNextEntry()) != null) {
                String entryName = entry.getName();
                Path targetDirResolved = target.resolve(entryName);
                Path newDestPath = targetDirResolved.normalize();
                if (entry.isDirectory()) {
                    newDestPath = Paths.get(destDir + "/" + entryName);
                    Files.createDirectories(newDestPath);
                } else {
                    Files.copy(ti, newDestPath, StandardCopyOption.REPLACE_EXISTING);
                }
            }
            flag = true;
        } catch (Exception e) {
            log.info("解压tar.gz文件失败:{},{}", sourceFile, e);
        }
        return flag;
    }

/**
     * @description:  解压zip到指定的文件夹
     * @date: 2023/5/29 17:56
     * @param sourceFile  源文件绝对路径
     * @param destDir  要解压到的目录地址
     * @return boolean
     */
public static boolean unZip(String zipPath, String descDir) {
        boolean flag = false;
        try (FileInputStream fis = new FileInputStream(zipPath);
             ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis), Charset.forName("GBK"))) {
            ZipEntry entry;
            while ((entry = zis.getNextEntry()) != null) {
                log.info("Unzipping: " + entry.getName());
                if (entry.getName().endsWith("/")) {
                    File pathFile = new File(descDir + "/" + entry.getName());
                    if (!pathFile.exists()) {
                        pathFile.mkdirs();
                    }
                    continue;
                }
                int size;
                byte[] buffer = new byte[2048];
                String destFile = descDir + "\\" + entry.getName();
                destFile = destFile.replaceAll("\\\\", "/");
                File fileOut = new File(destFile);
                try (FileOutputStream fos = new FileOutputStream(fileOut);
                     BufferedOutputStream bos = new BufferedOutputStream(fos, buffer.length)) {
                    while ((size = zis.read(buffer, 0, buffer.length)) != -1) {
                        bos.write(buffer, 0, size);
                    }
                    bos.flush();
                }
            }
            flag = true;
        } catch (IOException e) {
            log.info("解压zip文件失败:{},{}", zipPath, e);
        }
        return flag;
    }


/**
     * @description:  解压rar到指定的文件夹
     * @date: 2023/5/29 17:56
     * @param sourceFile  源文件绝对路径
     * @param destDir  要解压到的目录地址
     * @return boolean
     */
public static boolean unRar(String rarPath, String descDir){
        if (!descDir.endsWith("/")) {
            descDir = descDir + "/";
        }
        File pathFile = new File(descDir);
        if (!pathFile.exists()) {
            pathFile.mkdirs();
        }
        File rarFile = new File(rarPath);
        try {
            RandomAccessFile randomAccessFile = new RandomAccessFile(rarFile.toString(), "r");
            IInArchive archive = SevenZip.openInArchive(null, new RandomAccessFileInStream(randomAccessFile));
            int[] in = new int[archive.getNumberOfItems()];
            for (int i = 0; i < in.length; i++) {
                in[i] = i;
            }
            archive.extract(in, false, new ExtractCallback(archive, pathFile.getAbsolutePath() + "/"));
            archive.close();
            randomAccessFile.close();
            return true;
        } catch (Exception e) {
            log.error("解压rar出错 {}", e.getMessage());
            return false;
        }
    }

/**
     * @description:  解压rar辅助类
     */
public class ExtractCallback implements IArchiveExtractCallback{

        private Logger log = LoggerFactory.getLogger(ExtractCallback.class);

        private int index;
        private IInArchive inArchive;
        private String ourDir;

        public ExtractCallback(IInArchive inArchive, String ourDir) {
            this.inArchive = inArchive;
            this.ourDir = ourDir;
        }

        @Override
        public void setCompleted(long arg0) throws SevenZipException {
        }

        @Override
        public void setTotal(long arg0) throws SevenZipException {
        }

        @Override
        public ISequentialOutStream getStream(int index, ExtractAskMode extractAskMode) throws SevenZipException {
            this.index = index;
            String path = (String) inArchive.getProperty(index, PropID.PATH);
            final boolean isFolder = (boolean) inArchive.getProperty(index, PropID.IS_FOLDER);
            String finalPath = path;
            File newfile = null;
            try {
                String fileEnd = "";
                //对文件名,文件夹特殊处理
                if (finalPath.contains(File.separator)) {
                    fileEnd = finalPath.substring(finalPath.lastIndexOf(File.separator) + 1);
                } else {
                    fileEnd = finalPath;
                }
                finalPath = finalPath.substring(0, finalPath.lastIndexOf(File.separator) + 1) + fileEnd;
                //目录层级
                finalPath = finalPath.replaceAll("\\\\", "/");
                String suffixName = "";
                int suffixIndex = fileEnd.lastIndexOf(".");
                if (suffixIndex != -1) {
                    suffixName = fileEnd.substring(suffixIndex + 1);
                }
                newfile = createFile(isFolder, ourDir + finalPath);
                final boolean directory = (boolean) inArchive.getProperty(index, PropID.IS_FOLDER);
            } catch (Exception e) {
                log.error("rar解压失败{}", e.getMessage());
            }
            File finalFile = newfile;
            return data -> {
                save2File(finalFile, data);
                return data.length;
            };
        }

        @Override
        public void prepareOperation(ExtractAskMode arg0) throws SevenZipException {
        }

        @Override
        public void setOperationResult(ExtractOperationResult extractOperationResult) throws SevenZipException {
        }

        public  File createFile(boolean isFolder, String path) {
            //前置是因为空文件时不会创建文件和文件夹
            File file = new File(path);
            try {
                if (!isFolder) {
                    File parent = file.getParentFile();
                    if ((!parent.exists())) {
                        parent.mkdirs();
                    }
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                } else {
                    if ((!file.exists())) {
                        file.mkdirs();
                    }
                }
            } catch (Exception e) {
                log.error("rar创建文件或文件夹失败 {}", e.getMessage());
            }
            return file;
        }

        public  boolean save2File(File file, byte[] msg) {
            OutputStream fos = null;
            try {
                fos = new FileOutputStream(file, true);
                fos.write(msg);
                fos.flush();
                return true;
            } catch (FileNotFoundException e) {
                log.error("rar保存文件失败{}", e.getMessage());
                return false;
            } catch (IOException e) {
                log.error("rar保存文件失败{}", e.getMessage());
                return false;
            } finally {
                try {
                    fos.close();
                } catch (IOException e) {
                    log.error("rar保存文件失败{}", e.getMessage());
                }
            }
        }
}

 

标签:解压,JAVA,tar,zip,return,boolean,File,new,String
From: https://www.cnblogs.com/guliang/p/17520953.html

相关文章

  • 八期day05-java基础
    1Java环境搭建#合伙人---》下次讲#java:做反编译,发现好多java代码看不太懂,有些加密算法,也不太好破---》接下来的时候,要学习java开发 -找到加密算法---》chatgpt,让它给你写---》转成python---》自己手动调#java编译型语言 -javase:java基础---》python中变量定义,函数,......
  • 八期day06-java基础2
    零python和java字节字符串比较0.1java字节数组和字符串相互转换//1字符串转字节数组v4="彭于晏"byte[]b=v4.getBytes();//默认utf8形式System.out.println(b);//输出对象形式,看不到字节数组System.out.println(Arrays.toString(b));//try{//......
  • java List复制:浅拷贝与深拷贝
    Java的拷贝可以分为三种:浅拷贝(ShallowCopy)、深拷贝(DeepCopy)、延迟拷贝(LazyCopy)。在java中除了基本数据类型之外(int,long,short等),还存在引用数据类型,例如String以及对象实例。对于基本数据类型,实际上是拷贝它的值,而对于引用数据类型,拷贝的就是它的引用,并没有创建一个新的......
  • java -- 常见API` 1
        ......
  • Failed to copy artifact. Failed to install artifact-\target\classes (Access is
    Failedtocopyartifact.Failedtoinstallartifact-\target\classes(Accessisdenied)<!--<plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-jar-plugin</artifactId><version>2.3.2</version&......
  • javac: invalid target release: 1.6
    Itriedtobuildaprojectonnetbeanswhenthiserrorcameup:javac:invalidtargetrelease:1.6Usage:javac<options><sourcefiles>wherepossibleoptionsinclude:-gGeneratealldebugginginfo-g:noneGeneratenodebugginginfo-......
  • 关于java 虚拟机栈
    线程的栈是在哪里提出来了的?Oracle官网的java虚拟机规范里面,2.5.2章节。网址:https://docs.oracle.com/javase/specs/jvms/se11/html/jvms-2.html下图就是我们常说的java虚拟机栈。java虚拟机栈的栈帧具体是什么?栈帧(StackFrame)是以方法(Method)为基础的。栈帧里面有局部变量表(......
  • JAVA_OPTS
    JAVA_OPTS是一个环境变量,它可用于设置Java虚拟机(JVM)的运行参数。通过设置JAVA_OPTS环境变量,您可以为Java应用程序提供各种运行时配置。以下是使用JAVA_OPTS环境变量进行常见配置的示例:指定堆内存大小:-Xmx:设置最大堆内存大小,如 -Xmx2G 表示将最大堆内存设置为2GB......
  • 什么是JAVA内容仓库(Java Content Repository)
    内容仓库模型JSR-170是这样定义内容仓库的,内容仓库由一组workspace(工作空间)组成,这些workspace通常应该包含相似的内容。一个内容仓库有一个到多个workspace。每个workspace都是一个树状结构,都有一个唯一的树根节点(rootnode)。树上的item(元素)或者是个node(节点)或者是个property......
  • JSON中,java.lang.NoClassDefFoundError: net/sf/ezmorph/Morpher问题解决
    使用JSON,在SERVLET或者STRUTS的ACTION中取得数据时,如果会出现异常:java.lang.NoClassDefFoundError:net/sf/ezmorph/Morpher是因为需要的类没有找到,一般,是因为少导入了JAR包,使用JSON时,除了要导入JSON网站上面下载的json-lib-2.2-jdk15.jar包之外,还必须有其它几个依赖包:commons-bean......