1. 程式人生 > >java實現Windows開機自啟動

java實現Windows開機自啟動

java實現Windows開機自啟動

自己寫的java小程式執行在Windows系統上,想要為程式新增開機自啟動設定怎麼辦?

總體思路是,生成啟動檔案寫入到系統的開機啟動項中即可,如果已打包成exe可執行程式,則生成快捷方式寫入開機啟動項,如果是其他檔案,可以將啟動指令碼寫入bat檔案然後寫入開機啟動項。

簡單寫一些方法,如何建立exe的快捷方式詳見:https://blog.csdn.net/rico_zhou/article/details/80062917

直接上程式碼:

	// 寫入快捷方式 是否自啟動,快捷方式的名稱,注意字尾是lnk
	public boolean setAutoStart(boolean yesAutoStart, String lnk) {
		File f = new File(lnk);
		String p = f.getAbsolutePath();
		String startFolder = "";
		String osName = System.getProperty("os.name");
		String str = System.getProperty("user.home");
		if (osName.equals("Windows 7") || osName.equals("Windows 8") || osName.equals("Windows 10")
				|| osName.equals("Windows Server 2012 R2") || osName.equals("Windows Server 2014 R2")
				|| osName.equals("Windows Server 2016")) {
			startFolder = System.getProperty("user.home")
					+ "\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup";
		}
		if (osName.endsWith("Windows XP")) {
			startFolder = System.getProperty("user.home") + "\\「開始」選單\\程式\\啟動";
		}
		if (setRunBySys(yesAutoStart, p, startFolder, lnk)) {
			return true;
		}
		return false;
	}

	// 設定是否隨系統啟動
	public boolean setRunBySys(boolean b, String path, String path2, String lnk) {
		File file = new File(path2 + "\\" + lnk);
		Runtime run = Runtime.getRuntime();
		File f = new File(lnk);

		// 複製
		try {
			if (b) {
				// 寫入
				// 判斷是否隱藏,注意用系統copy佈置為何隱藏檔案不生效
				if (f.isHidden()) {
					// 取消隱藏
					try {
						Runtime.getRuntime().exec("attrib -H \"" + path + "\"");
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if (!file.exists()) {
					run.exec("cmd /c copy " + formatPath(path) + " " + formatPath(path2));
				}
				// 延遲0.5秒防止複製需要時間
				Thread.sleep(500);
			} else {
				// 刪除
				if (file.exists()) {
					if (file.isHidden()) {
						// 取消隱藏
						try {
							Runtime.getRuntime().exec("attrib -H \"" + file.getAbsolutePath() + "\"");
						} catch (IOException e) {
							e.printStackTrace();
						}
						Thread.sleep(500);
					}
					run.exec("cmd /c del " + formatPath(file.getAbsolutePath()));
				}
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	// 解決路徑中空格問題
	private String formatPath(String path) {
		if (path == null) {
			return "";
		}
		return path.replaceAll(" ", "\" \"");
	}

需要開機自啟動則寫入啟動檔案,不需要開啟自啟動則刪除啟動檔案,實現案例:https://blog.csdn.net/rico_zhou/article/details/80062893