packageblockchaincode.utils;importjava.io.BufferedInputStream;importjava.io.BufferedOutputStream;importjava.io.File;importjava.io.FileNotFoundException;importjava.io.FileOutputStream;importjava.io.IOException;importjava.util.Enumeration;importjava.util.jar.JarEntry;importjava.util.jar.JarFile;importjava.util.jar.JarOutputStream;importjava.util.zip.ZipEntry;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;/*** jar包压缩跟解压工具类
*@authorWangSong
**/
public classJarUtil {private static Logger log = LoggerFactory.getLogger(JarUtil.class);privateJarUtil(){}/*** 复制jar by JarFile
*@paramsrc
*@paramdes
*@throwsIOException*/
public static void copyJarByJarFile(File src , File des) throwsIOException{//重点
JarFile jarFile = newJarFile(src);
Enumeration jarEntrys =jarFile.entries();
JarOutputStream jarOut= new JarOutputStream(new BufferedOutputStream(newFileOutputStream(des)));byte[] bytes = new byte[1024];while(jarEntrys.hasMoreElements()){
JarEntry entryTemp=jarEntrys.nextElement();
jarOut.putNextEntry(entryTemp);
BufferedInputStream in= newBufferedInputStream(jarFile.getInputStream(entryTemp));int len = in.read(bytes, 0, bytes.length);while(len != -1){
jarOut.write(bytes,0, len);
len= in.read(bytes, 0, bytes.length);
}
in.close();
jarOut.closeEntry();
log.error("复制完成: " +entryTemp.getName());
}
jarOut.finish();
jarOut.close();
jarFile.close();
}/*** 解压jar文件by JarFile
*@paramsrc
*@paramdesDir
*@throwsFileNotFoundException
*@throwsIOException*/
public static void unJarByJarFile(File src , File desDir) throwsFileNotFoundException, IOException{
JarFile jarFile= newJarFile(src);
Enumeration jarEntrys =jarFile.entries();if(!desDir.exists())
desDir.mkdirs();//建立用户指定存放的目录
byte[] bytes = new byte[1024];while(jarEntrys.hasMoreElements()){
ZipEntry entryTemp=jarEntrys.nextElement();
File desTemp= new File(desDir.getAbsoluteFile() + File.separator +entryTemp.getName());if(entryTemp.isDirectory()){ //jar条目是空目录
if(!desTemp.exists())
desTemp.mkdirs();
log.error("makeDir" +entryTemp.getName());
}else{ //jar条目是文件//因为manifest的Entry是"META-INF/MANIFEST.MF",写出会报"FileNotFoundException"
File desTempParent =desTemp.getParentFile();if(!desTempParent.exists())desTempParent.mkdirs();
BufferedInputStream in= newBufferedInputStream(jarFile.getInputStream(entryTemp));
BufferedOutputStream out= new BufferedOutputStream(newFileOutputStream(desTemp));int len = in.read(bytes, 0, bytes.length);while(len != -1){
out.write(bytes,0, len);
len= in.read(bytes, 0, bytes.length);
}
in.close();
out.flush();
out.close();
log.error("解压完成: " +entryTemp.getName());
}
}
jarFile.close();
}
}