我想在Java中以编程方式查找.exe文件路径,例如:
我尝试过的方法是对系统文件进行排序,直到找到“skype.exe”,但这会花费大量的时间和资源。
是否有任何黑客可以使它几乎是即时的,比如可能是一个Win_Api函数/ cmd命令,或者是在整个文件系统中进行排序,直到找到该程序的唯一方式?
答案 0 :(得分:1)
我实际上发现了一些有效的东西,虽然不是最快的,但只需要大约100毫秒 - 500毫秒即可完成,具体取决于exe。
您需要使用运行时进程来执行此操作。
基本上你进入驱动器的根目录,然后在cmd中使用这些命令搜索文件系统。
cd \
dir /s /b mytool.exe
这将返回文件路径。
我的代码:
(Hackish我知道)
try {
Process p = Runtime.getRuntime().exec("./res/getPrograms.bat " + exeName);
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while(true) {
line = input.readLine();
if(line == null) {
break;
}
System.out.println(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
.bat文件(我将参数“eclipse.exe”传递给bat文件,表示为%1):
cd \
dir /s /b %1
exit
输出变为:
C:\Users\Mitchell\workspace\Remote Admin>cd \
C:\>dir /s /b eclipse.exe
C:\eclipse\eclipse.exe
答案 1 :(得分:1)
作为@Minor's answer的扩展,如果您希望通过将搜索限制为仅在Windows上当前“安装”的程序来提高性能,则以下注册表项包含有关“已安装”程序的信息。
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall
使用PowerShell,您可以访问存储在这些密钥中的已安装软件的属性。这里特别感兴趣的是IntallLocation
属性。
然后,您只需修改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返回的InstallLocations
,尽管该脚本在cmd中工作正常。从概念上讲,这个解决方案是合理的。