java实现文件夹下解压jar包和zip包

比如解压下列jar包:D:\ProtexScan\example\example.jar
将项目打成jar包后,执行:java -jar decompression_tools-1.0-SNAPSHOT.jar D:\ProtexScan
解压完成后会在D:\ProtexScan生成一个target目录和extractLog.txt日志文件,所有解压后的文件按照原目录结构放置在target目录下。

package common;

import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Zip;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;

import java.io.*;
import java.util.Enumeration;

/**
 * 文件解压缩工具类
 *
 */
public class FileOperateUtil {

    public static void setLogPath(String logPath) {
        FileOperateUtil.logPath = logPath;
    }

    //    private static Logger logger = Logger.getLogger(FileOperateUtil.class);
    private static String logPath = "";

    public static String getLogPath() {
        return logPath;
    }

    /**
     * 压缩文件
     *
     * @param zipFilePath 压缩的文件完整名称(目录+文件名)
     * @param srcPathName 需要被压缩的文件或文件夹
     */
    public void compressFiles(String zipFilePath, String srcPathName) {
        File zipFile = new File(zipFilePath);
        File srcdir = new File(srcPathName);
        if (!srcdir.exists()) {
            throw new RuntimeException(srcPathName + "不存在!");
        }
        Project prj = new Project();
        FileSet fileSet = new FileSet();
        fileSet.setProject(prj);
        if (srcdir.isDirectory()) { //是目录
            fileSet.setDir(srcdir);
            fileSet.setIncludes("*.csv"); //包括哪些文件或文件夹 eg:zip.setIncludes("*.java");
            //fileSet.setExcludes(...); //排除哪些文件或文件夹
        } else {
            fileSet.setFile(srcdir);
        }
        Zip zip = new Zip();
        zip.setProject(prj);
        zip.setDestFile(zipFile);
        zip.setEncoding("gbk"); //gbk编码进行压缩,注意windows是默认以gbk编码进行压缩的
        zip.addFileset(fileSet);
        zip.execute();
//        logger.debug("---compress files success---");
    }

    /**
     * 解压文件到指定目录
     *
     * @param //zipFile 目标文件
     * @param //descDir 解压目录
     * @author isDelete 是否删除目标文件
     */
    @SuppressWarnings("unchecked")
    public void unZipFiles(String zipFilePath, String fileSavePath, boolean isDelete) {
        FileOperateUtil fileOperateUtil = new FileOperateUtil();
        boolean isUnZipSuccess = true;
        try {
            (new File(fileSavePath)).mkdirs();
            File f = new File(zipFilePath);
            if ((!f.exists()) && (f.length() <= 0)) {
                throw new RuntimeException("not find "+zipFilePath+"!");
            }
            //一定要加上编码,之前解压另外一个文件,没有加上编码导致不能解压
            ZipFile zipFile = new ZipFile(f, "gbk");
            String gbkPath, strtemp;
            Enumeration<ZipEntry> e = zipFile.getEntries();
            while (e.hasMoreElements()) {
                org.apache.tools.zip.ZipEntry zipEnt = e.nextElement();
                gbkPath = zipEnt.getName();
                strtemp = fileSavePath + File.separator + gbkPath;
                if (zipEnt.isDirectory()) { //目录
                    File dir = new File(strtemp);
                    if (!dir.exists()) {
                        dir.mkdirs();
                    }
                    continue;
                } else {
                    // 读写文件
                    InputStream is = zipFile.getInputStream(zipEnt);
                    BufferedInputStream bis = new BufferedInputStream(is);
                    // 建目录
                    String strsubdir = gbkPath;
                    for (int i = 0; i < strsubdir.length(); i++) {
                        if (strsubdir.substring(i, i + 1).equalsIgnoreCase("/")) {
                            String temp = fileSavePath + File.separator
                                    + strsubdir.substring(0, i);
                            File subdir = new File(temp);
                            if (!subdir.exists())
                                subdir.mkdir();
                        }
                    }
                    FileOutputStream fos = new FileOutputStream(strtemp);
                    BufferedOutputStream bos = new BufferedOutputStream(fos);
                    int len;
                    byte[] buff = new byte[5120];
                    while ((len = bis.read(buff)) != -1) {
                        bos.write(buff, 0, len);
                    }
                    bos.close();
                    fos.close();
                }
            }
            zipFile.close();
        } catch (Exception e) {
//            logger.error("解压文件出现异常:", e);
            isUnZipSuccess = false;
            System.out.println("extract file error: " + zipFilePath);
            fileOperateUtil.WriteStringToFile(fileOperateUtil.logPath, "extract file error: " + zipFilePath);
        }
        /**
         * 文件不能删除的原因:
         * 1.看看是否被别的进程引用,手工删除试试(删除不了就是被别的进程占用)
         2.file是文件夹 并且不为空,有别的文件夹或文件,
         3.极有可能有可能自己前面没有关闭此文件的流(我遇到的情况)
         */
        if (isDelete && isUnZipSuccess) {
            boolean flag = new File(zipFilePath).delete();
//            logger.debug("删除源文件结果: " + flag);
            fileOperateUtil.WriteStringToFile(fileOperateUtil.logPath, "delete " + zipFilePath + "result: " + flag);
        }
//        logger.debug("compress files success");
    }

    /**
     * 删除指定文件夹下所有文件
     * param path 文件夹完整绝对路径
     *
     * @param path
     * @return
     */

    public static boolean delAllFile(String path) {
        System.out.println(path);
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
                boolean success = (new File(path + "/" + tempList[i])).delete();
                flag = success;
            }
        }
        return flag;
    }

    /**
     * 复制单个文件
     *
     * @param oldPath String 原文件路径 如:c:/fqf.txt
     * @param newPath String 复制后路径 如:f:/fqf.txt
     * @return boolean
     */
    public void copyFile(String oldPath, String newPath) {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(oldPath));
            bos = new BufferedOutputStream(new FileOutputStream(newPath));

            int hasRead = 0;
            byte b[] = new byte[2048];
            while ((hasRead = bis.read(b)) > 0) {
                bos.write(b, 0, hasRead);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.flush();
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 复制整个文件夹内容
     * @param oldPath String 原文件路径 如:c:/fqf
     * @param newPath String 复制后路径 如:f:/fqf/ff
     * @return boolean
     */
    public void copyFolder(String oldPath, String newPath) {
        System.out.println("copy path: " + oldPath);
        try {
            (new File(newPath)).mkdirs(); //如果文件夹不存在 则建立新文件夹
            File a = new File(oldPath);
            String[] file = a.list();
            File temp = null;
            for (int i = 0; i < file.length; i++) {
                if (oldPath.endsWith(File.separator)) {
                    temp = new File(oldPath + file[i]);
                } else {
                    temp = new File(oldPath + File.separator + file[i]);
                }

                if (temp.isFile()) {
                    FileInputStream input = new FileInputStream(temp);
                    FileOutputStream output = new FileOutputStream(newPath + "/" +
                            (temp.getName()).toString());
                    byte[] b = new byte[5120];
                    int len;
                    while ((len = input.read(b)) != -1) {
                        output.write(b, 0, len);
                    }
                    output.flush();
                    output.close();
                    input.close();
                }
                if (temp.isDirectory()) {//如果是子文件夹
                    copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);
                }
            }
        } catch (Exception e) {
            System.out.println("复制整个文件夹内容操作出错");
            e.printStackTrace();
        }

    }

    /**
     * 写内容到指定文件
     * @param filePath
     * @param content
     */
    public void WriteStringToFile(String filePath, String content) {
        try {
            FileWriter fw = new FileWriter(filePath, true);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(content + "\r\n");// 往已有的文件上添加字符串
            bw.close();
            fw.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}


package common;

import java.io.File;

public class Execute {

    public void extractFiles(String strPath) {
        FileOperateUtil fileOperateUtil = new FileOperateUtil();
        File dir = new File(strPath);
        File[] files = dir.listFiles(); // 该文件目录下文件全部放入数组
        if (files != null) {
            for (int i = 0; i < files.length; i++) {
                String fileName = files[i].getName();

                if (!files[i].isDirectory() && (fileName.endsWith(".jar") || fileName.endsWith(".zip"))) { // 判断文件名是否以.jar结尾
                    String sourceFilePath = files[i].getAbsolutePath();
                    System.out.println("extract file: " + sourceFilePath);
                    fileOperateUtil.WriteStringToFile(fileOperateUtil.getLogPath(), "extract file: " + sourceFilePath);
                    String dirName = fileName.substring(0, fileName.length() - 4);
                    String resultPath = sourceFilePath.replace(fileName, dirName);

                    fileOperateUtil.unZipFiles(sourceFilePath, resultPath, true);
                }
            }

        }
    }

    public static void main(String[] args) throws Exception {
        FileOperateUtil fileOperateUtil = new FileOperateUtil();
        String rootPath = args[0];

        if ("".equals(rootPath) || rootPath == null) {
            System.out.println("please input extract path:");
            fileOperateUtil.WriteStringToFile(fileOperateUtil.getLogPath(), "please input extract path:");
        }

//        String rootPath = "D:\\SVNhome\\test";
//        fileOperateUtil.delAllFile(rootPath);

        if (rootPath.endsWith("\\")) {
            rootPath = rootPath.substring(0, rootPath.length() - 1);
        }
        fileOperateUtil.setLogPath(rootPath + "\\extractLog.txt");

        long startTime = System.currentTimeMillis();
        long endTime = 0;
        System.out.println("extract path: " + rootPath);
        fileOperateUtil.WriteStringToFile(fileOperateUtil.getLogPath(), "extract path: " + rootPath);

        Execute execute = new Execute();

        File dir = new File(rootPath);
        File[] files = dir.listFiles();
        if (files != null) {
            int filesNum = files.length;
            for (int i = 0; i < filesNum; i++) {
                String fileName = files[i].getName();
                if (!fileName.endsWith(".svn") && !fileName.endsWith("extractLog.txt") && !fileName.endsWith("target")) {
                    fileOperateUtil.WriteStringToFile(fileOperateUtil.getLogPath(), "copy path: " + rootPath + "\\" + fileName);
                    if (files[i].isDirectory()) {
                        fileOperateUtil.copyFolder(rootPath + "\\" + fileName, rootPath + "\\target\\" + fileName);
                        execute.extractFiles(rootPath + "\\target\\" + fileName);
                    } else {
                        fileOperateUtil.copyFile(rootPath + "\\" + fileName, rootPath + "\\target\\" + fileName);
                    }
                }
            }
        }

        endTime = System.currentTimeMillis();    //获取结束时间

        System.out.println("程序运行时间:" + (endTime - startTime) / 1000 + "s");    //输出程序运行时间
        fileOperateUtil.WriteStringToFile(fileOperateUtil.getLogPath(), "程序运行时间:" + (endTime - startTime) / 1000 + "s");
    }
}

pom文件

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>test</groupId>
  <artifactId>decompression_tools</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>test1</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.ant</groupId>
      <artifactId>ant</artifactId>
      <version>1.8.2</version>
    </dependency>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.16</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <version>1.2.1</version>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>shade</goal>
            </goals>
            <configuration>
              <transformers>
                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                  <mainClass>common.Execute</mainClass>
                </transformer>
              </transformers>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>


  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
注:下文中的 *** 代表文件名中的版本号。 # 【javacv-***.jar中文文档.zip】 中含: 中文文档:【javacv-***-javadoc-API文档-中文(简体)版.zipjar包下载地址:【javacv-***.jar下载地址(官方地址+国内镜像地址).txt】 Maven依赖:【javacv-***.jar Maven依赖信息(可用于项目pom.xml).txt】 Gradle依赖:【javacv-***.jar Gradle依赖信息(可用于项目build.gradle).txt】 源代码下载地址:【javacv-***-sources.jar下载地址(官方地址+国内镜像地址).txt】 # 本文件关键字: javacv-***.jar中文文档.zip,java,javacv-***.jar,org.bytedeco,javacv,***,cl.eye,jar包,Maven,第三方jar包,组件,开源组件,第三方组件,Gradle,bytedeco,中文API文档,手册,开发手册,使用手册,参考手册 # 使用方法: 解压javacv-***.jar中文文档.zip】,再解压其中的 【javacv-***-javadoc-API文档-中文(简体)版.zip】,双击 【index.html】 文件,即可用浏览器打开、进行查看。 # 特殊说明: ·本文档为人性化翻译,精心制作,请放心使用。 ·只翻译了该翻译的内容,如:注释、说明、描述、用法讲解 等; ·不该翻译的内容保持原样,如:类名、方法名、名、类型、关键字、代码 等。 # 温馨提示: (1)为了防止解压后路径太长导致浏览器无法打开,推荐在解压时选择“解压到当前文件夹”(放心,自带文件夹,文件不会散落一地); (2)有时,一套Java组件会有多个jar,所以在下载前,请仔细阅读本篇描述,以确保这就是你需要的文件; # Maven依赖: ``` <dependency> <groupId>org.bytedeco</groupId> <artifactId>javacv</artifactId> <version>***</version> </dependency> ``` # Gradle依赖: ``` Gradle: implementation group: 'org.bytedeco', name: 'javacv', version: '***' Gradle (Short): implementation 'org.bytedeco:javacv:***' Gradle (Kotlin): implementation("org.bytedeco:javacv:***") ``` # 含有的 Java package(): ``` cl.eye org.bytedeco.javacv ``` # 含有的 Java class(类)(此处仅列举3个): ``` cl.eye.CLCamera org.bytedeco.javacv.AndroidFrameConverter org.bytedeco.javacv.BaseChildSettings ...... ```
解压JavaJAR包,可以使用以下命令: 在当前文件夹下使用命令行(cmd)解压jar包,可以使用命令"jar -xvf",后接待解压jar包的文件名。例如,要解压名为"shop-order-0.0.1-SNAPSHOT.jar"的jar包,可以使用命令"jar -xvf shop-order-0.0.1-SNAPSHOT.jar"。 另外,如果你不想解压整个jar包,而只是想更新其中的某个文件,可以使用命令"jar -uvf",后接待更新的jar包的文件名和要修改的文件路径。例如,要修改名为"shop-order-0.0.1-SNAPSHOT.jar"的jar包中的"BOOT-INF/classes/application.properties"文件,可以使用命令"jar -uvf shop-order-0.0.1-SNAPSHOT.jar BOOT-INF/classes/application.properties"。 JAR文件是Java的一种文档格式,非常类似ZIP文件。唯一的区别在于JAR文件中多出了一个META-INF/MANIFEST.MF文件。该文件在生成JAR文件时会自动创建(也可以自行创建)。除了解压和更新文件,你还可以使用JAR文件进行反编译操作。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [JavaJar包反编译,解压压缩](https://blog.csdn.net/lishangke/article/details/127850114)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值