作为@Minor's answer 的扩展,如果您想通过将搜索限制为仅搜索当前在 Windows 上“安装”的程序来提高性能,以下注册表项包含有关“已安装”程序的信息。
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall
使用 powershell,您可以访问存储在这些密钥中的已安装软件的属性。特别感兴趣的是InstallLocation 属性。
然后,您只需修改 Java 代码以利用另一个批处理脚本来检索这些安装位置,并专门针对 exe 文件的这些安装位置。
getInstalledPrograms.bat
@echo off
powershell -Command "Get-ChildItem -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall, HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall | Get-ItemProperty | Where-Object {$_.DisplayName -match \"%1\"} | Select-Object -Property InstallLocation"
exit
getPrograms.bat
@echo off
cd %1
dir /b /s "*%2*.exe"
exit
Java 示例:
String search = "skype";
try {
Process getInstalled = Runtime.getRuntime().exec("./src/getInstalledPrograms.bat " + search);
BufferedReader installed = new BufferedReader(new InputStreamReader(getInstalled.getInputStream()));
String install;
String exe;
int count = 0;
while(true) {
install = installed.readLine();
if(install == null) {
break;
}
install = install.trim();
// Ignore powershell table header and newlines.
if(count < 3 || install.equals("")) {
count++;
continue;
}
Process getExes = Runtime.getRuntime().exec("./src/getPrograms.bat " + "\"" + install + "\"");
BufferedReader exes = new BufferedReader(new InputStreamReader(getExes.getInputStream()));
while(true) {
exe = exes.readLine();
if(exe == null) {
break;
}
exe = exe.trim();
System.out.println(exe);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
目前我的 Java 示例与 getInstalledPrograms.bat 返回的 InstallLocation 重复,尽管该脚本在 cmd 中运行良好。不过从概念上讲,这个解决方案是合理的。