execute file .lnk in Java

自作多情 提交于 2019-12-04 19:50:22

Use a ProcessBuilder:

ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "C:\\temp\\file.lnk");
Process process = pb.start();

Call process.getInputStream() and process.getErrorStream() to read the output and error output of the process.

On Windows, you could use rundll:

Runtime.getRuntime().exec("rundll32 SHELL32.DLL,ShellExec_RunDLL " +  
    "\Path\to\File.lnk");

Java has no support for OS specific features, but java.awt.Desktop.open should do.

Or you can use ProcessBuilder... but it will need a path to the actual rundll32. I did it, while trying to sort an odd bug in my little "Hierarchic Send to" app.

(I hate that windows, post-XP "flatten", the links in the "Send to" option to a stupid list; as a tree, I could navigate better the forty odd small options that I use on my system )

Here is the code of the action calling a link (or whatever type of file):

ArrayList<String> app = new ArrayList<>();
app.add("C:\\Windows\\System32\\rundll32.exe");
app.add("SHELL32.DLL,ShellExec_RunDLL");
app.add(file.getAbsolutePath());

// Args are passed by windows when it launches the "More Sends" jar
for (int i = 0; args != null && i < args.length; i++) {
    app.add(args[i]);
}

ProcessBuilder b = new ProcessBuilder(app);
// The logger thread hangs till the called process does not die... not ideal
 // log(
    b.start()
// )
;

However, the whole shenhanigan of calling a windows .lnk through Java can give pretty confusing results.

A direct link to x.jar may open the jar with the system Java VM, but a direct link to installed jre/bin/javaw.exe -jar "x.jar" may fail, with a "Windows can't locate the file" message.

This, while another jar called the exact same way will execute flawessly.

Though, I might have to look at the alternate streams of the .lnk, as some are copies from my old PC...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!