importjava.io.BufferedReader;importjava.io.File;importjava.io.FileReader;importjava.io.FileWriter;importjava.io.IOException;importjava.io.InputStreamReader;importjava.util.ArrayList;importjava.util.List;importjava.util.regex.Matcher;importjava.util.regex.Pattern;/*** Java调用cmd下的tracert(路由跟踪命令)并获得不重复IP地址存储文件中。
*@authorpochonlee
* @time 2009/11/29/ 21:40:40*/publicclassTracertIp {/***@paramargs
*@throwsIOException*/publicstaticvoidmain(String[] args)throwsIOException {
System.out.println("Begin
");
Listlist=ReadFile("config.ini");
ProcessCmd(list);
System.out.println("Over
");
}privatestaticvoidSaveFile(String filePath, ListinString)
{
FileWriter fw=null;try{
fw=newFileWriter(newFile(filePath),true);for(inti=0; i
{
fw.write(inString.get(i)+"\n");
}
fw.close();
}catch(IOException e) {
System.out.println("File Save Exception :"+e.getMessage());
}
}privatestaticListReadFile(String filePath)throwsIOException
{
Listlist=null;
BufferedReader br=newBufferedReader(newFileReader(newFile(filePath)));
String line=null;
list=newArrayList();while((line=br.readLine())!=null)
{
list.add(line);
}
br.close();returnlist;
}privatestaticvoidProcessCmd(Listlist)
{
String ip="([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}";
Process process=null;
ProcessBuilder processBuilder=newProcessBuilder(list);
processBuilder.redirectErrorStream(true);
ListlistResult=newArrayList();try{
process=processBuilder.start();
BufferedReader br=newBufferedReader(newInputStreamReader(process.getInputStream()));
String line=null;
String tmp=null;while((line=br.readLine())!=null)
{
Pattern pattern=Pattern.compile(ip);
Matcher matcher=pattern.matcher(line);if(matcher.find())
{
tmp=matcher.group();if(!listResult.contains(tmp))
{
listResult.add(tmp);
}
}
}
SaveFile("ip.address",listResult);
process.waitFor();
}catch(IOException e) {
e.printStackTrace();
}catch(InterruptedException e) {
e.printStackTrace();
}finally{if(process!=null)
{
process.destroy();
}
}
process.destroy();
}
}
简单的说一下,就是ip是采用正则表达式的方式判断的。