如何删除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);
}
/**
* @param filenames : ["meta-inf/bckey.dsa"],注意斜杠
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);
}