java - 从 Java 创建快捷方式文件

标签 java windows

一个困扰我数周的问题是如何从 Java 创建快捷方式文件。现在,在我说任何其他内容之前,我已经在 Google 上(以及这个网站;包括这个:Creating shortcut links (.lnk) from Java)查看了所有内容,试图找到有用的东西。我需要的不是创建快捷方式的安装程序包,而是从代码创建快捷方式。我所说的快捷方式是指通常在桌面上找到的 .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 快捷方式,所以我相信我可能采取了错误的方法。如果您能给我任何帮助/链接,我将不胜感激。

最佳答案

我可以在 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");

希望这对你有帮助:)

亲切的问候

约书亚·弗兰克

关于java - 从 Java 创建快捷方式文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13145942/

相关文章:

java - 如何添加显示的数字

java - Android WebView不显示本地IP地址

javascript - 如何将 servlet 中的字符串解析为 javascript 并创建包含数组值的格式化对象

java - ServiceTracker 找到哪些服务

windows - 使用 .bat 文件从 Windows 启动中删除程序

windows - 调试 Windows 消息内容和目标的好方法是什么?

javax.crypto.IllegalBlockSizeException : Input length must be multiple of 16 when decrypting with padded cipher in tcp

java - 将 SQLite 数据库从 Android 转换为 Windows (Java)

windows - 卸载以前的版本安装新版本的安装项目

windows - Windows 服务器 2012r2 上的 Docker