实现自己的项目打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 unzip
log.info("Zip【"+ file2.getPath() +"】file "+ (++i));
String parentPath = file2.getAbsolutePath().replace(path, "") ; //get the ref classpath path
jarOut.putNextEntry(new JarEntry(parentPath)) ;
input = new FileInputStream(file2) ;
while((temp = input.read()) != -1){
jarOut.write(temp) ;
}
input.close() ;
}
}
}
}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Abellor

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值