i try to do some cmd command in java, my script:
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");
}
}
and the output result:
run:
List of de开发者_开发百科vices attached
0160880B0401F006 device
how can i catch the part of that result: "0160880B0401F006" and put into a list on my gui?
thanks before
I'd use a regular expression (untested):
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);
}
}
You should also read When Runtime.exec() won't, in case you run into any problems with executing the external command.
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");
}
}
精彩评论