欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

用代码更新你的jar包

程序员文章站 2024-02-19 19:53:52
假设目录结构是maven标准结构复制代码 代码如下:-src-target-test.jar(你需要更新的jar包) 复制代码 代码如下:package com.foo....

假设目录结构是maven标准结构

复制代码 代码如下:

-src
-target
-test.jar(你需要更新的jar包)

复制代码 代码如下:

package com.foo.common.base.utils.development;

import static org.junit.assert.*;

import java.io.file;
import java.io.ioexception;
import java.util.date;
import java.util.properties;

import org.apache.commons.io.fileutils;
import org.junit.test;
import org.slf4j.logger;
import org.slf4j.loggerfactory;
import org.springframework.core.io.classpathresource;

public class jarupdater {
 public static final logger logger = loggerfactory
   .getlogger(jarupdater.class);

 @test
 /**
  * 更新com目录下的所有文件到jar的对应目录结构中去
  *
  * 一次成功的代码更新,我们断言jar的大小是不一样的
  */
 public void updateclass() throws ioexception, interruptedexception {

  classpathresource mypath = new classpathresource(
    "jarupdaterconfig.properties");
  properties p = new properties();
  p.load(mypath.getinputstream());

  classupdater classupdater = new classupdater().applysettings(p);

  classupdater.compileandcopyclass();

  string workingdirectory = p.getproperty("workingdirectory");
  string jar4updatename = p.getproperty("jar4updatename");
  // class compile path
  string updatesourcepath = workingdirectory + "target";
  // class root folder
  string updatesourcedir = "com";

  date startdate = new date();

  file myjar = new file(workingdirectory + jar4updatename);
  if (!myjar.isfile()) {
   logger.error("file with following path {} does not exist.",
     jar4updatename);
   return;
  }
  long oldlength = myjar.length();
  logger.info("now ready to update jar file with name:{},size:{}",
    myjar.getname(), myjar.length());
  string mycommand = "jar uf " + workingdirectory + jar4updatename
    + " -c " + updatesourcepath + " " + updatesourcedir;
  logger.info("update command【{}】", mycommand);

  runtime.getruntime().exec(mycommand);

  while (!fileutils.isfilenewer(myjar, startdate)) {
   logger.info("sleep for two seconds,checking changes...");
   thread.sleep(2000);
  }
  assertnotequals(
    "jar may not be updated successfully,check the code please",
    oldlength, myjar.length());
  logger.info("now finish update jar file with size:{}", myjar.length());
 }
}