0%

java实现开机自启(快捷方式)

文章字数:200,阅读全文大约需要1分钟

主要思路是将快捷方式放入windows的开机自启目录中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// 写入快捷方式 是否自启动,快捷方式的名称,注意后缀是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(" ", "\" \"");
}