几个星期以来一直困扰我的一个问题是如何从 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/");
}
}
我玩弄了它,并设法在我的桌面上创建了一个 .lnk 快捷方式。但是,我发现了两个问题:
尽管路径将其链接到正确的图标,但我无法更改图标。我创建了一条路径,将我引导至 C:/Users/USER/Documents,但是,每当我单击快捷方式时,它都会将我带到 C:/。当我删除快捷方式时,对话框确实显示路径是 file:////C:/Users/USER/Documents。
我知道上面的这段代码最初是为了创建 Internet Shortcuts,所以我相信我可能采取了错误的方法。如果您能给我任何帮助/链接,我将不胜感激。
我可以在 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();如果要更改快捷方式的图标,请使用:
ShellLink sl = ...; sl.setIconLocation("/path/to/icon/file");希望这对你有帮助:)
亲切的问候
约书亚·弗兰克