本帖最后由 ZhangYL 于 2014-8-2 07:28 编辑
package cn.test;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;
/**
* 把以下IP存入一个txt文件,编写程序把这些ip按数值大小
* 从小到大排序并打印出来
*
* @author 娱乐来宾
*61.54.231.245
61.54.231.9
61.54.231.246
61.54.231.48
61.54.231.249
*/
public class Test5 {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
BufferedReader bufr = new BufferedReader(new FileReader("F:\\Java_ZhangYL\\Caculate\\Test_30\\src\\cn\\test\\IPAddress.txt"));
String line = null;
TreeSet<String> ts = new TreeSet<String>(new IPAddressComparator());
while((line = bufr.readLine())!= null)
{
ts.add(line);
}
Iterator<String> it = ts.iterator();
while(it.hasNext())
{
String str = it.next();
System.out.println(str);
}
bufr.close();
}
}
class IPAddressComparator implements Comparator
{
public int compare(Object o1,Object o2)
{
String str1 = (String)o1;
String str2 = (String)o2;
String[] arr1 = str1.split("\\.");
String[] arr2 = str2.split("\\.");
for(int i = 0 ; i < 4 ; i++)
{
if((arr1.compareTo(arr2))>0)
{
//System.out.println(arr1+".."+arr2);
return 1;
}
if(arr1.equals(arr2))
{
//System.out.println(arr1+".."+arr2);
continue;
}
if((arr1.compareTo(arr2))<0)
{
//System.out.println(arr1+".."+arr2);
return -1;
}
}
return 0;
}
}
|
|