我需要根据 COM# 名称确定 COM 端口的“友好名称”。
我找到了一些答案,但它们要么适用于 C#,要么适用于 C++。 java中有一个方法(可能是纯的)吗?
最佳答案
经过长时间的搜索,我最终编写了以下似乎对我有用的类(class);显然这是一个仅限 Win32 的东西。
我希望它能帮助其他人。
package registry;
import static com.sun.jna.platform.win32.WinReg.HKEY_LOCAL_MACHINE;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.sun.jna.platform.win32.Advapi32Util;
import com.sun.jna.platform.win32.Win32Exception;
public class FriendlyName {
private static final String ENUM = "SYSTEM\\CurrentControlSet\\Enum\\USB";
private Map<String, String> friendlyNames;
private static final String KEY = "HARDWARE\\DEVICEMAP\\SERIALCOMM";
public FriendlyName() {
friendlyNames = new HashMap<>();
Pattern p = Pattern.compile(".*?\\(([^)]+)\\)");
for (String dev : Advapi32Util.registryGetKeys(HKEY_LOCAL_MACHINE, ENUM)) {
String sb = ENUM + "\\" + dev;
for (String itm : Advapi32Util.registryGetKeys(HKEY_LOCAL_MACHINE, sb)) {
String si = sb + "\\" + itm;
String fn = null;
try {
fn = Advapi32Util.registryGetStringValue(HKEY_LOCAL_MACHINE, si, "FriendlyName");
} catch (Win32Exception e) {}
if (fn != null) {
Matcher m = p.matcher(fn);
if (m.matches()) {
friendlyNames.put(m.group(1), fn);
}
}
}
}
}
String get(String key) {
return friendlyNames.get(key);
}
public String getCOM(String name) {
try {
for (Entry<String, Object> sub : Advapi32Util.registryGetValues(HKEY_LOCAL_MACHINE, KEY).entrySet()) {
String n = (String) sub.getValue();
String fn = get(n);
if (fn != null && fn.startsWith(name))
return n;
}
} catch (IllegalArgumentException e) {
System.err.println(e);
}
return null;
}
public static void main(String[] args) {
FriendlyName fn = new FriendlyName();
System.out.println(fn.getCOM(args[0]));
}
}
关于java - 在java中的windows下根据给定的COMx名称查找com端口的 "FriendlyName",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30883825/