如何删除jar包中的指定文件呢?
当然使用解压缩软件(rar,zip,7z)肯定没问题.但是我想自动化,图形界面的工具就无能为力了.
核心方法:
- /***
- * 删除jar包中的内容
- * @param jarPath
- * @param fileName : "META-INF/BCKEY.DSA"
- * @throws IOException
- * @throws ArchiveException
- */
- public static void deleteFileInJar(String jarPath,String fileName) throws IOException, ArchiveException{
- List<String>fileNames=new ArrayList<String>();
- if(!ValueWidget.isNullOrEmpty(fileName)){
- fileNames.add(fileName);}
- deleteFileInJar(jarPath, fileNames);
- }
- /**
- * 删除jar包中的内容
- * @param jarPath
- * @param fileNames : ["META-INF/BCKEY.DSA"],注意斜杠
- * @throws IOException
- * @throws ArchiveException
- */
- public static void deleteFileInJar(String jarPath,List<String>fileNames) throws IOException, ArchiveException{
- List<ZipFileBean> zipFiles = CompressZipUtil
- .deCompressRecursionFileList(jarPath, "", true);
- List<ZipApkFile> zipApkFiles = extendZipFileBean(zipFiles,fileNames);
- CompressZipUtil.setPrint(false);
- File newFile=new File(jarPath + ".bak");
- while(newFile.exists()){
- //若bak文件存在,则循环修改名称,只到文件不存在
- System.out.println("file exist:"+newFile.getAbsolutePath());
- newFile=new File(jarPath + RandomUtils.getTimeRandom2());
- }
- CompressZipUtil.persistenceZip(newFile, zipApkFiles);
- File jarFile=new File(jarPath);
- System.out.println("delete old jar:"+jarFile.getAbsolutePath());
- boolean isSuccess=jarFile.delete();
- if(!isSuccess){
- System.out.println("删除失败:"+jarFile.getAbsolutePath());
- }else{
- System.out.println("modify name");
- newFile.renameTo(jarFile);
- }
- }
使用说明:
比如我想删除jar(zip)包中的config\manual.properties
zip包结构:
main方法如下:
- public static void main(String[] args) throws IOException, ArchiveException {
- String jarPath="D:\\bin\\config\\config.zip";
- deleteFileInJar(jarPath, "config/manual.properties"/*"META-INF/BCKEY.DSA"*/);
- System.out.println("jarPath:"+jarPath);
- }