現在有一個關於自動更新的需求:我們在一程序中下載更新文件到update文件中,要求將update中所有文件移動到父路徑中,替換當前的所有文件,替換完畢後啓動一個exe文件。
我們的更新遷移程序就是一個簡單的jar包。
廢話不多說上代碼。
更新的代碼CopyUtil.java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
public class CopyUtil {
/**
* 移動指定文件或文件夾(包括所有文件和子文件夾)
*
* @param fromDir
* 要移動的文件或文件夾
* @param toDir
* 目標文件夾
* @throws Exception
*/
public static void MoveFolderAndFileWithSelf(String from, String to)
throws Exception {
try {
File dir = new File(from);
// 目標
// to =to+ File.separator + dir.getName();
File moveDir = new File(to);
if (dir.isDirectory()) {
if (!moveDir.exists()) {
moveDir.mkdirs();
}
} else {
File tofile = new File(to);
dir.renameTo(tofile);
return;
}
// 文件一覽
File[] files = dir.listFiles();
if (files == null)
return;
// 文件移動
for (int i = 0; i < files.length; i++) {
System.out.println("文件名:" + files[i].getName());
if (files[i].isDirectory()) {
MoveFolderAndFileWithSelf(files[i].getPath(), to
+ File.separator + files[i].getName());
// 成功,刪除原文件
files[i].delete();
}
File moveFile = new File(moveDir.getPath() + File.separator
+ files[i].getName());
// 目標文件夾下存在的話,刪除
if (moveFile.exists()) {
moveFile.delete();
}
files[i].renameTo(moveFile);
}
} catch (Exception e) {
throw e;
}
}
public static void main(String[] args) throws Exception {
CopyUtil databean = new CopyUtil();
//獲取當前jar的路徑 如d:\workfile\update\update.jar
String path = CopyUtil.class.getProtectionDomain().getCodeSource()
.getLocation().getPath();
//獲取當前jar所在的文件夾路徑 如d:\workfile\update
File file_ = new File(path);
//更新文件存放目錄
String from_path = file_.getParent() +File.separator+ "update";
//需要替換的文件存放目錄
String to_path = file_.getParent();
//執行替換動作
databean.MoveFolderAndFileWithSelf(from_path, to_path);
//啓動exe文件
String doUtils=file_.getParent()+File.separator+"ERP.exe";
try{
Runtime.getRuntime().exec("cmd /c "+doUtils);
}catch(Exception e){}
}
}
將程序打包成可運行的jar包,然後既可以通過bat腳本啓動
工具包的文件如下:
直接執行bat文件會有cmd的褐色彈框出現,通過在vbs中調用bat腳本去掉褐色彈框。
具體jar文件打包運行可以參考我的另一篇文檔