几个星期困扰我的一个问题是如何从Java创建快捷方式文件.在我说出任何其他内容之前,我已经遍布谷歌(以及此网站;包括:从Java创建快捷方式链接(.lnk))试图找到有用的东西.我需要的不是一个创建快捷方式的安装程序包,而是从代码创建快捷方式.我的快捷方式是一个.lnk文件,通常可以在桌面上找到.
我找到的一个有用的东西是这个程序:
Java代码:
import java.io.*;
public class WindowsUtils {
private WindowsUtils() { }
private static final String WINDOWS_DESKTOP = "Desktop";
public static String getWindowsCurrentUserDesktopPath() { //return the current user desktop path
return System.getenv("userprofile") + "/" + WINDOWS_DESKTOP ;
}
public static void createInternetShortcutOnDesktop(String name, String target) throws IOException {
String path = getWindowsCurrentUserDesktopPath() + "/"+ name + ".URL";
createInternetShortcut(name, path, target, "");
}
public static void createInternetShortcutOnDesktop(String name, String target, String icon) throws IOException {
String path = getWindowsCurrentUserDesktopPath() + "/"+ name + ".URL";
createInternetShortcut(name, path, target, icon);
}
public static void createInternetShortcut(String name, String where, String target, String icon) throws IOException {
FileWriter fw = new FileWriter(where);
fw.write("[InternetShortcut]\n");
fw.write("URL=" + target + "\n");
if (!icon.equals("")) {
fw.write("IconFile=" + icon + "\n");*
}
fw.flush();
fw.close();
}
public static void main(String[] args) throws IOException {
WindowsUtils.createInternetShortcutOnDesktop("GOOGLE", "http://www.google.com/");
}
}
Run Code Online (Sandbox Code Playgroud)
我玩弄它,并设法在我的桌面上创建.lnk快捷方式.但是,我发现了两个问题:
我无法更改图标,尽管路径将其链接到正确的图标.我创建了一条路径,引导我进入C:/ Users/USER/Documents,然而,每当我点击它的快捷方式时我都会转到C:/.当我删除快捷方式时,对话框确实显示路径为file://// C:/ Users/USER/Documents.
我知道上面的代码最初是为了创建Internet快捷方式,所以我相信我可能采取了错误的方法.我很感激你能给我的任何帮助/链接.
小智 7
我可以在GitHub上推荐这个存储库:
https://github.com/BlackOverlord666/mslinks
在那里,我找到了一个简单的解决方案来创建快捷方式:
ShellLink.createLink("path/to/existing/file.txt", "path/to/the/future/shortcut.lnk");
如果您想阅读快捷方式:
File shortcut = ...;
String pathToExistingFile = new ShellLink(shortcut).resolveTarget();
Run Code Online (Sandbox Code Playgroud)
如果要更改快捷方式的图标,请使用:
ShellLink sl = ...;
sl.setIconLocation("/path/to/icon/file");
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助你:)
亲切的问候
Josua Frank
http://www.mindfiresolutions.com/Creating-shortcut-from-a-Java-Application-1712.php
一个使用名为 jShellLink 的 jni 库的漂亮而简单的教程