我尝试在java中执行一些cmd命令,我的脚本:
public void test(){
try{
Runtime rt=Runtime.getRuntime();
Process p = rt.exec("cmd /c "+"adb devices");
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while((line=input.readLine())!=null){
System.out.print(line);
}
}catch(Exception e){
System.out.println("process failed");
}
}
和输出结果:
run:
List of devices attached
0160880B0401F006 device
我怎么能抓住那个结果的一部分:“0160880B0401F006”并把我的gui列入一个列表?
之前感谢
答案 0 :(得分:0)
我使用a regular expression(未经测试):
Pattern p = Pattern.compile("(\d+)\s*(.*)");
while((line=input.readLine())!=null){
Matcher m = p.matcher(line);
if (m.matches()) {
String id = matcher.group(1);
String name = matcher.group(2);
// do whatever you want with your values here
System.out.println("id: " + id + ", name: " + name);
}
}
如果您在执行外部命令时遇到任何问题,还应阅读When Runtime.exec() won't。
答案 1 :(得分:0)
public void test(){
try{
Runtime rt=Runtime.getRuntime();
Process p = rt.exec("cmd /c "+"adb devices");
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line=input.readLine();//discard first line
List<String> deviceList=new ArrayList<String>();
while((line=input.readLine())!=null){
deviceList.add(line.split(" ")[0]);
}
System.out.println("Device list "+deviceList);
}catch(Exception e){
System.out.println("process failed");
}
}