如何用Java创建.lnk文件?

时间:2014-06-19 19:46:26

标签: java windows shortcut

我找到了许多用于处理windows(.lnk)快捷方式的解析解决方案,但我需要通过我的Java-Tool创建它们。

所以我的问题是:

  • 如何创建它们?
  • (或者最好使用Files.createSymbolicLink?) - 问题是它们的Filesize为零,并且不会被视为" normal"文件(因此,当我想删除空文件夹时,符号快捷方式(内部)也会被删除,因为它们不会被识别为"正常"文件))

2 个答案:

答案 0 :(得分:1)

我们发现最可靠的方法是生成一个临时的.js文件,然后生成一个WScript子进程。它感觉非常糟糕,但它避免了任何Java弱点并且适用于较旧的JRE(这对我们很重要,因为Files.createSymbolicLink甚至可能不适用于我们的一些用例。)

结果看起来模糊如下。您可以将其重写为使用Path而不是File和其他NIO.2功能等。所有传入的变量都是普通的String实例,在底部描述;它们可能是空的但永远不会为空。

重要的是要注意,此代码用于在Windows“特殊文件夹”中创建快捷方式,而不仅仅是在任意位置。你可以为此进行调整。

File scriptFile = File.createTempFile ("whatever", ".js");

try (PrintWriter script = new PrintWriter(scriptFile)) {
    script.printf("try {\n");
    script.printf("wshshell = WScript.CreateObject(\"WScript.Shell\")\n");
    script.printf("specDir = wshshell.SpecialFolders(\"%s\")\n", folder);
    script.printf("shortcut = wshshell.CreateShortcut(specDir + \"\\\\%s.lnk\")\n", shortcutName);
    script.printf("shortcut.TargetPath = \"%s\"\n", target);
    script.printf("shortcut.Arguments = \"%s\"\n", arguments);
    script.printf("shortcut.WindowStyle = 1\n");
    script.printf("shortcut.HotKey = \"\"\n");
    if (icon.length() > 0)
        script.printf("shortcut.IconLocation = \"%s\"\n", icon);
    script.printf("shortcut.Description = \"%s\"\n", description);
    script.printf("shortcut.WorkingDirectory = \"%s\"\n", workingDir);
    script.printf("shortcut.Save()\n");
    script.printf("} catch (err) {\n");
    // Commented by default
    script.printf("/*WScript.Echo(\"name:\")\nWScript.Echo(err.name)\n");
    script.printf("WScript.Echo(\"message:\")\nWScript.Echo(err.message)\n");
    script.printf("WScript.Echo(\"description:\")\nWScript.Echo(err.description)\n");
    script.printf("WScript.Echo(\"stack:\")\nWScript.Echo(err.stack)\n");
    script.printf("*/\n");
    script.printf("WScript.Quit(1)\n");
    script.printf("}\n");
    script.close();

    // now run cscript.exe with arguments "//nologo" and the full
    // path to 'script', using something like ProcessBuilder and Process
}

您可以测试进程的退出值,如果为零,则删除临时文件。如果出现问题,您可以将文件留待调查,包括手动编辑脚本以取消注释底部的错误转储。

folder是目标文件夹的特殊Windows名称,例如“SendTo”或“StartMenu”等。完整列表位于MSDN的某处,但要记住的主要事项是它们不是'这些文件夹必须是简单的英文名称。

shortcutName例如是“我的程序快捷方式”。 target是您认为的,应该是获得最安全结果的完整途径。

icon字符串是一个时髦的Windows,你给出一个图标文件名和索引号,所以像“MyApp.ico,0”。上面的代码将空图标字符串视为使用系统默认值。

description成为快捷方式的属性 - >评论字段。如果您不需要设置它们,argumentsworkingDir可以留空。

答案 1 :(得分:1)

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

希望这有助于你:)

亲切的问候 Josua Frank