如何在Java中获取快捷方式路径,实现跨设备无需修改路径运行?
实现自动获取桌面快捷方式并打开的方案
1. 获取当前用户桌面路径(兼容多语言系统)
Windows系统的桌面路径因语言版本可能存在差异(如英文为Desktop,中文为“桌面”),以下提供两种可靠的获取方式:
方案A:纯Java读取注册表实现
无需引入第三方库,通过调用系统命令读取注册表中的桌面路径:
import java.io.BufferedReader; import java.io.InputStreamReader; public class DesktopPathUtil { public static String getDesktopPath() throws Exception { // 调用reg命令读取注册表项 Process process = Runtime.getRuntime().exec("reg query \"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders\" /v Desktop"); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "GBK")); String line; while ((line = reader.readLine()) != null) { if (line.contains("REG_SZ")) { // 提取并格式化路径 String[] parts = line.split("REG_SZ"); return parts[1].trim().replace("%USERPROFILE%", System.getProperty("user.home")); } } // 读取失败时 fallback 到默认路径 return System.getProperty("user.home") + "\\Desktop"; } }
方案B:引入JNA库实现(更简洁)
若允许引入第三方依赖,可通过JNA直接调用Windows Shell API获取路径,Maven依赖如下:
<dependency> <groupId>net.java.dev.jna</groupId> <artifactId>jna</artifactId> <version>5.13.0</version> </dependency> <dependency> <groupId>net.java.dev.jna</groupId> <artifactId>jna-platform</artifactId> <version>5.13.0</version> </dependency>
获取桌面路径的代码:
import com.sun.jna.platform.win32.Shell32; import com.sun.jna.platform.win32.ShlObj; import com.sun.jna.platform.win32.WinDef; public class DesktopPathUtil { public static String getDesktopPath() { WinDef.HWND hwnd = null; char[] path = new char[ShlObj.MAX_PATH]; Shell32.INSTANCE.SHGetFolderPath(hwnd, ShlObj.CSIDL_DESKTOPDIRECTORY, null, ShlObj.SHGFP_TYPE_CURRENT, path); return new String(path).trim(); } }
2. 构造快捷方式路径并启动
拿到桌面路径后,拼接快捷方式的完整路径,再通过ProcessBuilder调用:
import java.io.File; public class ShortcutLauncher { public static void main(String[] args) throws Exception { String desktopPath = DesktopPathUtil.getDesktopPath(); String shortcutPath = desktopPath + "\\notepad.lnk"; File shortcutFile = new File(shortcutPath); // 先判断快捷方式是否存在 if (!shortcutFile.exists()) { System.err.println("桌面快捷方式 notepad.lnk 不存在"); return; } ProcessBuilder pb = new ProcessBuilder("cmd", "/c", shortcutPath); Process p = pb.start(); p.waitFor(); } }
额外建议
如果你的核心需求只是打开记事本程序,更推荐直接调用notepad.exe,无需依赖桌面快捷方式,代码更简洁且不受快捷方式是否存在的影响:
public static void main(String[] args) throws Exception { ProcessBuilder pb = new ProcessBuilder("notepad.exe"); Process p = pb.start(); p.waitFor(); }
内容的提问来源于stack exchange,提问作者Jeremy
相关产品推荐
相关产品推荐

