我正在编写一个安卓应用来执行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