在C/S端上,软件都会涉及到版本的更新。
首先创建一个类,这是版本更新的类
package zhuxiaosha;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class Upgrader {
public static String currentversion = "1";//当前版本号,这里是从本地打包成exe文件中取得的版本号
public static String newversion = currentversion; //最新版本号,这里是从服务器配置中取得的版本号
public static boolean downloaded = false;//下载完成与否
public static boolean errored = false;//下载出错与否
//public static String versinurl = "http://11.212.150.117:8922/war/version.txt"; //版本存放地址
public static String versionurl ="http://localhost:8083/main/version.txt"; ///本地tomcat版本存放地址
public static String jarurl = "http://localhost:8083/main/main.jar"; //本地jar存放地址
//public static String jarurl = "http://11.212.150.117:8922/war/main.jar"; //jar存放地址
public static String description = "";//新版本更新信息
/**
* 静默下载最新版本
*/
public static void dowload() {
try {
downLoadFromUrl(jarurl, "main.jar", "C:/Users/dell/Desktop/update");//第二个参数为保存的文件名,第三个参数是保存的路径名
downloaded = true;
} catch (Exception e) {
downloaded = false;
errored = true;
e.printStackTrace();
}
}
/**
* 重启完成更新
*/
public static void restart() {
try {
if(!currentversion.equals(newversion)) {
Runtime.getRuntime().exec("cmd /k start .\\update.bat");
}
Main.close(); //关闭程序以便重启
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 获取服务器配置的最新版本号
*/
public static void getServerVersion(){
URL url;
try {
url = new URL(versionurl);
URLConnection connection = url.openConnection();
InputStream is = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is,"gb2312"));
String line = null;
String getLine = null;
while((line=br.readLine())!=null) {
getLine=line;
}
newversion = getLine;
System.out.println(newversion.toString()+"---------------------");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取最新版本号
*/
public static void getNewVersion() {
// String json = sendGetRequest(versinurl);
// JSONObject ob = JSONObject.parseObject(json);
//去取txt或者json文件里的当前版本号
try {
File txtFile = new File("C:/Users/dell/Desktop/update/version.txt");
//File txtFile = new File(versinurl);
InputStreamReader reader = new InputStreamReader(new FileInputStream(txtFile));
BufferedReader sb = new BufferedReader(reader);
String getLine = "";
String line;
while((line=sb.readLine())!=null) {
getLine=line;
}
currentversion = getLine;
System.out.println(currentversion);
description = "更新";
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 启动后自动更新
*/
public static void autoupgrade() {
getNewVersion();
getServerVersion();
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 {
if(!currentversion.equals(newversion)) {
//更新version
File txtFile = new File("C:/Users/dell/Desktop/update/version.txt");
//File txtFile = new File(versinurl);
FileWriter writer = new FileWriter(txtFile);
BufferedWriter out = new BufferedWriter(writer);
out.write(newversion);
out.flush();
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);
System.out.println("文件保存的路径:"+savePath);
if (!saveDir.exists()) {
saveDir.mkdir();
}
File file = new File(saveDir + File.separator + fileName);
System.out.println("这是main.jar的路径:"+file.getPath());
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();
}
public static void main(String[] args) {
autoupgrade();
}
}
public static String versionurl ="http://localhost:8083/main/version.txt"; ///本地tomcat版本存放地址
public static String jarurl = "http://localhost:8083/main/main.jar"; //本地jar存放地址
这两个代码中,将txt和更新的jar包放入在tomcat目录下的webapps/Root,这里的main文件下是我新建的文件夹,main文件夹中包含jar包和version.txt。 version.txt内容写版本号(写一个数字也可以,如下图)。
downLoadFromUrl(jarurl, "main.jar", "C:/Users/dell/Desktop/update");//第二个参数为保存的文件名,第三个参数是保存的路径名
保存jar包和保存txt要在同一个文件下。
Main.close(); //关闭程序以便重启
这行代码只是模拟关闭程序的,close方法在类Main中