2013-05-30 26 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

相关问题