java 实现jar包解压再压缩(亲测)

网上很多关于jar包处理的都不全面,而却很多根本无法使用,这是我经过试验得出的有效方法。同时,关于jar包无法file.delete()删除jar包,查找了很多文章都没具体实现,此文也实现了,jar包解压,再压缩流程,覆盖旧jar包,也算删除了,另外提供一种方式删除jar包,方法如下

解压jar包

 /**
     * 解压jar包
     * @param  destDir 解压位置
     * @param  jarFile 需要解压的jar
     */
    public static void extractJar(String destDir,String jarFile) {
    //    String jarFile = "E:/test/com.ide.core_1.0.0.jar";
       if((jarFile == null) || (jarFile.equals("")) || !jarFile.endsWith(".jar")) {
            return;
        }
        try {
            JarFile jar = new JarFile(jarFile);
            Enumeration<?> enumeration = jar.entries();
            while(enumeration.hasMoreElements()) {
                JarEntry jarEntry = (JarEntry) enumeration.nextElement();
                String[] names = jarEntry.getName().split("/");
                for(int i = 0; i < names.length; i++) {
                    String path = destDir;
                    for(int j = 0; j < (i + 1); j++) {
                        path += File.separator + names[j];
                    }
                    File file = new File(path);
                    if(!file.exists()) {
                        if((i == (names.length - 1)) && !jarEntry.getName().endsWith("/")) {
                            file.createNewFile();
                        } else {
                            file.mkdirs();
                            continue;
                        }
                    } else {
                        continue;
                    }
                    InputStream is = jar.getInputStream(jarEntry);
                    FileOutputStream fos = new FileOutputStream(file);
                    while(is.available() > 0) {
                        fos.write(is.read());
                    }
                    fos.flush();
                    fos.close();
                }
            }

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

重新打包jar包

提供两种情况compressJar方法,直接指定需要压缩的文件夹,以及压缩路径;zipDirectory方法输入要解压文件的父文件,先遍历父文件下所有文件夹,再对文件夹压缩。

private static   List<String> list =new ArrayList();

   /**
     * 压缩jar包
     * @param srcPath 需要压缩的文件
     * @param targetPath 压缩的jar包,存放路劲
     */
    @SuppressWarnings("resource")
    public  static  void  compressJar(String srcPath,String targetPath) {
    	 FileOutputStream fileOutputStream=null;
    	 CheckedOutputStream cs =null;
         ZipOutputStream out=null;
         InputStream in=null;
         
        try {
            File file = new File(srcPath);
            //判断是否是目录
            if (file.isDirectory()) {
                if (list.size() > 0)
                    list.clear();
                byte b[] = new byte[128];
                // 压缩文件的保存路径
                String zipFile = targetPath + File.separator + file.getName() + ".jar";
                // 压缩文件目录
              //  String filepath = file.getAbsolutePath() + File.separator;
                List<String> fileList = allFile(srcPath+File.separator);

                 fileOutputStream = new FileOutputStream(zipFile);
                // 使用输出流检查
                 cs = new CheckedOutputStream(fileOutputStream, new CRC32());
                // 声明输出zip流
                 out = new ZipOutputStream(new BufferedOutputStream(
                        cs));

                for (int i = 0; i < fileList.size(); i++) {
                  
					 in = new FileInputStream((String) fileList.get(i));
                    String fileName = ((String) (fileList.get(i))).replace(File.separatorChar, '/');
                    System.out.println("ziping " + fileName);
                    String tmp = file.getName() + "/";
                    fileName = fileName.substring(fileName.lastIndexOf(tmp) + file.getName().length() + 1);
                    ZipEntry e = new ZipEntry(fileName);
                    out.putNextEntry(e);
                    int len = 0;
                    while ((len = in.read(b)) != -1) {
                        out.write(b, 0, len);
                    }
                    out.closeEntry();
                }               
                System.out.println("done!");
            }

        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
        	try {
        		if (in!=null) {
    				in.close();
    			}if (out!=null) {
    				   out.close();
    			}if (out!=null) {
    				  out.close();	
    			}if (cs!=null) {
    				 cs.close();
    			}if (fileOutputStream!=null) {
    				 fileOutputStream.close();
    			}
    			System.gc();//一定加上这个,否则源文件删除不了
			} catch (Exception e2) {
				// TODO: handle exception
			}
			
		}
    }





/**
 * jar压缩
 * @param parentDirPath 要压缩文件夹的父文件夹
 * @param targetPath 目标文件夹
 */
public   static  void zipDirectory(String parentDirPath,String targetPath)
{
    try {
        File dirFile= new File(parentDirPath);
        File[] listArr = dirFile.listFiles();
        for (File childFile  : listArr) {
            if(childFile.isDirectory())
            {
                if(list.size()>0)
                    list.clear();
                byte b[] =  new  byte[128];
                // 压缩文件的保存路径
                String zipFile =targetPath+File.separator+childFile.getName()+".jar";

                // 压缩文件目录
                String filepath =childFile.getAbsolutePath()+File.separator;

                List fileList = allFile(filepath);

                FileOutputStream fileOutputStream =  new FileOutputStream(zipFile);
                // 使用输出流检查
                CheckedOutputStream cs =  new CheckedOutputStream(fileOutputStream,  new CRC32());
                // 声明输出zip流
                ZipOutputStream out =  new ZipOutputStream( new BufferedOutputStream(
                        cs));

                for ( int i = 0; i < fileList.size(); i++) {
                    InputStream in =  new FileInputStream((String)fileList.get(i));
                    String fileName = ((String)(fileList.get(i))).replace(File.separatorChar,'/');
             
                    String tmp= childFile.getName()+"/";
                    fileName = fileName.substring(fileName.lastIndexOf(tmp)+childFile.getName().length()+1);
                    ZipEntry e =  new ZipEntry(fileName);
                    out.putNextEntry(e);
                    int len = 0;
                    while((len = in.read(b)) != -1) {
                        out.write(b,0,len);
                    }
                    out.closeEntry();
                }
                out.close();
          
            }
        }

    }  catch (Exception e) {
        e.printStackTrace();
    }

}

private  static List allFile(String path)
{

    File file =  new File(path);
    String[] array =  null;
    String sTemp = "";


    if(file.isDirectory())
    {
    } else{
        return  null;
    }
    array= file.list();
    if(array.length>0)
    {
        for( int i=0;i<array.length;i++)
        {
            sTemp = path+array[i];
            file =  new File(sTemp);
            if(file.isDirectory())
            {
                allFile(sTemp+"/");

            } else{
                list.add(sTemp);
            }
        }
    } else{
        return  null;
    }

    return list;
}

测试方法

public static void main(String[] args) throws Exception {
  String jarPath="E:\\test\\com.ide.platform_1.0.0\\library.jar";
         String jarPath1="E:\\test\\com.ide.core_1.0.0.jar";
         String jarPath2="E:\\test\\com.ide.project.core_1.0.0.jar";
         String destDir=  jarPath.substring(0,jarPath.lastIndexOf(".jar"));
        String destDir1=   jarPath1.substring(0,jarPath1.lastIndexOf(".jar"));
        String destDir2=  jarPath2.substring(0,jarPath2.lastIndexOf(".jar"));
        extractJar(destDir,jarPath);
        extractJar(destDir1,jarPath1);
        extractJar(destDir2,jarPath2);
        //重新压缩
        compressJar(destDir,jarPath.substring(0,jarPath.lastIndexOf("\\")));
  		compressJar(destDir1,jarPath1.substring(0,jarPath1.lastIndexOf("\\")));
        compressJar(destDir2,jarPath1.substring(0,jarPath2.lastIndexOf("\\")));
           }

删除jar包

	jarsPath:需要删除的jar包;如:E:\test\com.ide.project.core_1.0.0.jar
  Runtime.getRuntime().exec("cmd /c ping localhost -n 6 > nul && del "+jarsPath);

遍历删除压缩文件

 public static void main(String[] args) throws Exception {
  File file = new File("E:\\test\\com.ide.core_1.0.0");
 deleteFile(file );
}
  public static void deleteFile(File file){
        if(file == null || !file.exists()){
            return;
        }
        //获得文件对象的子文件对象列表
        File[] files = file.listFiles();
        //遍历这些子文件
        for (File f : files){
            //判断这些子文件是否是目录
            if(f.isDirectory()){
                //是文件夹的话继续递归 如果是发现文件直接删除
                deleteFile(f);
            }else {
                f.delete();
            }
        }
        //删除空文件夹
        file.delete();
    }
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
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、付费专栏及课程。

余额充值