2013-05-30 27 views
0

我正在編寫一個安卓應用來執行traceroute命令。如何從Java中的單個長字符串提取IP地址

當traceroute執行時,它將控制檯輸出放入一個非常長的單個字符串中。這是通過下面的代碼完成:

public void runAsRoot(String[] cmds) throws Exception { 


    Process p = Runtime.getRuntime().exec("su"); 
    DataOutputStream os = new DataOutputStream(p.getOutputStream()); 
    InputStream is = p.getInputStream(); 
    for (String tmpCmd : cmds) { 
     os.writeBytes(tmpCmd+"\n"); 
     int readed = 0; 
     byte[] buff = new byte[4096]; 

     // if cmd requires an output 
     // due to the blocking behaviour of read(...) 
     boolean cmdRequiresAnOutput = true; 
     if (cmdRequiresAnOutput) { 
      while(is.available() <= 0) { 
       try { Thread.sleep(10000); } catch(Exception ex) {} //timeout.. gotta watch this carefully. 
      } 

      while(is.available() > 0) { 

       readed = is.read(buff); 
       if (readed <= 0) break; 
       String seg = new String(buff,0,readed); 
       System.out.println("#> "+seg); 
       ListofIPs = seg; 


      } 
     } 
    }   
    os.writeBytes("exit\n"); 
    os.flush(); 
} 

這個字符串的輸出是這樣的: logcat output after printing the string

我想要做的就是利用這個輸出,而只提取IP地址,並把它們按順序成陣列。 這是我從哪裏開始都不知所措的地方。我在想一些類型的字符串操作,但不知道從哪裏開始。

如果任何人有任何想法或指針,我將不勝感激。

在此先感謝。

+0

看看String類的'.split()'方法。 – fge

+0

您是否熟悉正則表達式?如果沒有,請在這裏查看,這正是您所需要的:http://en.wikipedia.org/wiki/Regex – hellerve

+0

逐行閱讀..使用'.split(「」)',第二個元素將是IP地址。 – Shivam

回答

1

我會嘗試刪除第一行,然後嘗試使用空格使用String split。這樣你知道IP位於1,5,9,.. (1+4*n_iteration),或者你可以通過「ms」拆分,然後再按空格拆分。

+0

這是最好的。感謝分裂的想法 – Cheesegraterr

0

請嘗試使用regular expressions

在你的情況下,代碼會是這個樣子:

seg.split("[^((\d{1,3}\.){3}\d{1,3}]"); 

我沒有測試它,但它應該做的工作。您可以立即修補更優雅的解決方案。

+0

不會刪除ips並將剩下的剩餘部分留給我嗎? – Cheesegraterr

+0

不,因爲我加了[^ ...]這意味着*不*這個。基本上,它有點hacky:表達式就是一切*除了IP和IP將是你的數組元素。 – hellerve

相關問題