JavaFx的客户端程序更新实现(C/S架构,JavaFx客户端程序既是C)

效果:
1.点击“检测更新”
JavaFx的客户端程序更新实现(C/S架构,JavaFx客户端程序既是C)_第1张图片
2.弹出确认框
JavaFx的客户端程序更新实现(C/S架构,JavaFx客户端程序既是C)_第2张图片
3.点击确定后,cmd窗口一闪而过,覆盖jar包,重启程序

实现代码

1.fxml文件


    
        
        
        
    

2.Controller类方法

/**
 * 检测更新
 */
@FXML
public void toUpgrader() {
    // 从服务器获取最新版本号,和当前版本判断,从而判断出是否需要更新
    Upgrader.getnewversion();
    if (Upgrader.newversion > Upgrader.currentversion) {
        Alert confir = new Alert(Alert.AlertType.CONFIRMATION);
        confir.setHeaderText("");
        confir.setContentText("当前版本号"+Upgrader.currentversion+",最新版本号"+Upgrader.newversion+",建议您更新程序!");
        Optional type = confir.showAndWait();
        if (type.get()==ButtonType.OK){
            // 从服务器下载最新版本的jar文件到临时文件夹(所有java代码,包含更新的这一段,都导出为可执行的jar)
            Upgrader.dowload();
            // 复制临时文件夹的新版本覆盖运行目录文件,启动程序
            Upgrader.restart();
            // 关闭当前程序
            for(Stage forstage : StageController.stages.values()){
                forstage.close();
            }
            Platform.exit();
            System.exit(0);
        }
    } else {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setHeaderText("");
        alert.setContentText("当前版本号"+Upgrader.currentversion+",最新版本号"+Upgrader.newversion+",您已经是最新程序,无需更新!");
        alert.showAndWait();
    }
}

3.核心更新代码工具类

package com.cxbdapp.cadre.util;

import com.alibaba.fastjson.JSONObject;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * @ClassName Upgrader
 * @Description 自动更新客户端程序
 * @Author zhangxiaoyan
 * @Date 2019/5/8 9:30:00
 */
public class Upgrader {
	public static float currentversion = 1.02f;//当前版本号
	public static float newversion = currentversion; //最新版本号
	public static boolean downloaded = false;//下载完成与否
	public static boolean errored = false;//下载出错与否
	public static String versinurl = PropertyUtil.getLinkProperty("prefixWeb")+"/version/version.json"; //版本存放地址
	public static String jarurl = PropertyUtil.getLinkProperty("prefixWeb")+"/download/jar/cadre-client-0.0.1-SNAPSHOT-jfx.jar"; // jar存放地址
	public static String string2dowload = PropertyUtil.getLinkProperty("prefixWeb")+"/download/exe/cadre-client-setup.exe"; //备用更新方案
	public static String description = "";//新版本更新信息

	/**
	 * 静默下载最新版本
	 */
	public static void dowload() {
		try {
			downLoadFromUrl(jarurl, "dowloadtmp", "tmp");
			downloaded = true;
		} catch (Exception e) {
			downloaded = false;
			errored = true;
			e.printStackTrace();
		}

	}

	/**
	 * 重启完成更新
	 */
	public static void restart() {
		try {
			Runtime.getRuntime().exec("cmd /k start .\\update.vbs");
//            Main.close(); //关闭程序以便重启
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取最新版本号
	 */
	public static void getnewversion() {
		String json = sendGetRequest(versinurl);
		JSONObject ob =  JSONObject.parseObject(json);
		newversion = ob.getFloat("version");
		description = ob.getString("desc");
	}

	/**
	 * 启动后自动更新
	 */
	public static void autoupgrade() {
		getnewversion();
		dowload();
		restart();
	}

	/**
	 * 发get请求,获取文本
	 * @param getUrl
	 * @return 网页context
	 */
	public static String sendGetRequest(String getUrl) {
		StringBuffer sb = new StringBuffer();
		InputStreamReader isr = null;
		BufferedReader br = null;
		try {
			URL url = new URL(getUrl);
			URLConnection urlConnection = url.openConnection();
			urlConnection.setAllowUserInteraction(false);
			isr = new InputStreamReader(url.openStream(),"UTF-8");
			br = new BufferedReader(isr);
			String line;
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}


	/**
	 * 从网络Url中下载文件
	 *
	 * @param urlStr
	 * @param fileName
	 * @param savePath
	 * @throws IOException
	 */
	public static void downLoadFromUrl(String urlStr, String fileName, String savePath) throws IOException {
		URL url = new URL(urlStr);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		// 设置超时间为3秒
		conn.setConnectTimeout(3 * 1000);
		// 防止屏蔽程序抓取而返回403错误
		conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

		// 得到输入流
		InputStream inputStream = conn.getInputStream();
		// 获取自己数组
		byte[] getData = readInputStream(inputStream);

		// 文件保存位置
		File saveDir = new File(savePath);
		if (!saveDir.exists()) {
			saveDir.mkdir();
		}
		File file = new File(saveDir + File.separator + fileName);
		FileOutputStream fos = new FileOutputStream(file);
		fos.write(getData);
		if (fos != null) {
			fos.close();
		}
		if (inputStream != null) {
			inputStream.close();
		}

		System.out.println("info:" + url + " download success");

	}

	/**
	 * 从输入流中获取字节数组
	 *
	 * @param inputStream
	 * @return
	 * @throws IOException
	 */
	public static byte[] readInputStream(InputStream inputStream) throws IOException {
		byte[] buffer = new byte[1024];
		int len = 0;
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		while ((len = inputStream.read(buffer)) != -1) {
			bos.write(buffer, 0, len);
		}
		bos.close();
		return bos.toByteArray();
	}
}

4.实现覆盖重启的脚本文件(与jar放在一起)
JavaFx的客户端程序更新实现(C/S架构,JavaFx客户端程序既是C)_第3张图片
update.vbs

Set ws = CreateObject("Wscript.Shell")
ws.run "cmd /c update.bat",vbhide

update.bat

if not "%1"=="wkdxz" mshta vbscript:createobject("wscript.shell").run("""%~f0"" wkdxz",vbhide)(window.close)&&exit

@ping 127.0.0.1 -n 1 & xcopy /s/e/y .\tmp\dowloadtmp  .\cadre-client-0.0.1-SNAPSHOT-jfx.jar & ..\cadre-client-0.0.1-SNAPSHOT.exe

web端放jar和json文件即可

jar文件和json文件
JavaFx的客户端程序更新实现(C/S架构,JavaFx客户端程序既是C)_第4张图片
json文件:version.json

{
"version":1.1,
"desc":"1.引入自动跟新功能。\r\n2. 提高图片展示效率。\r\n3. 修复若干bug。",
"date":"2019-5-7 16:30:00"
}

参考:https://blog.csdn.net/sinat_34820292/article/details/81513611

你可能感兴趣的:(技术积累)