• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

用代码更新你的jar包

java 搞代码 4年前 (2022-01-05) 25次浏览 已收录 0个评论

这篇文章主要介绍了用程序代码更新com目录下的所有文件到jar的对应目录结构中去,这样可以做到自动更新程序吧

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

代码如下:
-src
-target
-test.jar(你需要更新的jar包)

代码如下:
package com.foo.common.base.utils.development;

import static org.junit.Assert.*;

import java.io.File;
import java来源[email protected]搞@^&代*@码)网.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());
 }
}

以上就是用代码更新你的jar包的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:用代码更新你的jar包

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址