我正在編寫一個安卓應用來執行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();
}
這個字符串的輸出是這樣的:
我想要做的就是利用這個輸出,而只提取IP地址,並把它們按順序成陣列。 這是我從哪裏開始都不知所措的地方。我在想一些類型的字符串操作,但不知道從哪裏開始。
如果任何人有任何想法或指針,我將不勝感激。
在此先感謝。
看看String類的'.split()'方法。 – fge
您是否熟悉正則表達式?如果沒有,請在這裏查看,這正是您所需要的:http://en.wikipedia.org/wiki/Regex – hellerve
逐行閱讀..使用'.split(「」)',第二個元素將是IP地址。 – Shivam