java实现Windows开机自启动

版权声明:本文为博主原创文章,未经博主允许不得转载! https://blog.csdn.net/rico_zhou/article/details/81301261

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

猜你喜欢

转载自blog.csdn.net/rico_zhou/article/details/81301261