2011-05-19 28 views
1

我試着做一些Java中的cmd命令,我的腳本:捕捉CMD輸出,並將其納入名錄的Java

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

之前,我會用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,萬一你碰上與執行外部命令的任何問題。

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"); 
     } 
    } 
+0

我嘗試使用你的方法。但它在這一行顯示錯誤: 列表 DeviceList = new ArrayList (); – paijho 2011-05-19 14:05:52

+0

錯誤是什麼?如果與進口有關,則添加 import java.util.ArrayList; import java.util.List; – 2011-05-20 05:12:45