我正在尝试使用“adb devices”命令提取Android的设备名称.. 通过使用这种方法,我成功地得到了:
public void newExec() throws IOException, InterruptedException, BadLocationException{
String adbPath = "/Volumes/development/android-sdk-macosx/tools/adb";
String cmd = adbPath+" "+"devices";
Process p;
p = Runtime.getRuntime().exec(cmd);
p.waitFor();
String line;
BufferedReader err = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while ((line = err.readLine()) != null) {
System.out.println(line);
}
err.close();
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line=input.readLine()) != null) {
//printing in the console
System.out.println(line);
}
input.close();
}
输出为:
List of devices attached
192.168.56.101:5555 device
我试图从此输出中仅获取设备名称:
192.168.56.101:5555
我以多种方式使用 split,例如:
String devices = "List of devices attached";
System.out.println(line.split(devices);
但这根本不起作用!
我想要的不是静态的方式,而是动态的方式。我的意思是,如果设备名称发生更改或者列出了多个设备,我想要一种仅提供设备名称的方法。 有办法吗?
抱歉,如果问题不太清楚,我对 Java 还不太熟悉:)
最佳答案
您可以尝试以下代码:
adb devices
的下一行输出是用制表符分隔的,因此我们必须使用“\t”作为参数。
List<String> deviceList = new ArrayList<String>();
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
if (line.endsWith("device")) {
deviceList.add(line.split("\\t")[0]);
}
}
for (String device : deviceList) {
System.out.println(device);
}
关于java - 提取字符串的设备名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29982246/