首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

兑现自己的项目打jar包工具类

2012-12-20 
实现自己的项目打jar包工具类自己用java.io.util.jar.*包下面的类写了一个打jar包的工具类,用法如下:将以

实现自己的项目打jar包工具类
自己用java.io.util.jar.*包下面的类写了一个打jar包的工具类,用法如下:

   将以下代码拷贝后在自己项目中新建一个java class(位置任意,只要在当前项目下即可),然后将代码粘贴保存后直接运行,就会在workspace里生成一个与项目名称相同的jar文件。


【Java Code】


-----------------------------------------------


import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.util.jar.JarEntry;import java.util.jar.JarOutputStream;import java.util.logging.Logger;/** * Make Jar util  * @author laiyujun@vip.qq.com * QQ: 381418273 * */public class MakeJarUtil {private Logger log = Logger.getLogger(this.getClass().getName()) ;private String path = System.getProperty("java.class.path") ;private String currentPath = path  + File.separator + this.getClass().getName().replaceAll("\\.", "\\\") +".class" ;private int i=0 ; // count file ;private int j=0 ; // count dir ;/** * @param args */public static void main(String[] args) {MakeJarUtil util = new MakeJarUtil() ;        if(util.path.indexOf(";") != -1){String path[] = util.path.split(";") ;util.path = path[0] ;}util.log.info("classpath:"+ util.path) ;File file = new File(util.path) ;File jarFile = new File(System.getProperty("user.dir") + ".jar") ;JarOutputStream jarOut =null ;long start = System.currentTimeMillis() ;try {jarOut = new JarOutputStream(new FileOutputStream(jarFile)) ;jarOut.setComment("This jar maked by my program") ;util.write(file, jarOut) ; //execute zip jar file} catch (Exception e) {e.printStackTrace();} finally {try {jarOut.close() ;} catch (IOException e) {e.printStackTrace();} finally {long end = System.currentTimeMillis() ;util.log.info("zip use total time【"+(end-start)+"ms】") ;}}}private void write(File file, JarOutputStream jarOut) throws Exception {if(null == file) return ;String path = this.path + File.separator ;int temp = 0 ;InputStream input = null ;File[] list = file.listFiles() ;for (File file2 : list) {if(file2.isDirectory()){log.info("Dir【"+ path + file2.getName() +"】..." + (++j));write(file2, jarOut) ;}else{if(!file2.getPath().equals(currentPath)){  //current file unziplog.info("Zip【"+ file2.getPath() +"】file "+ (++i));String parentPath = file2.getAbsolutePath().replace(path, "") ; //get the ref classpath pathjarOut.putNextEntry(new JarEntry(parentPath)) ;input = new FileInputStream(file2) ;while((temp = input.read()) != -1){jarOut.write(temp) ;}input.close() ;}}}}}

热点排行