public class Test06 {
public static void main(String[] args) throws Exception {
BufferedReader bufReader = new BufferedReader(new FileReader(new File(
"IP.txt")));
// 利用Set排序, 构造特定Comparator
Set<String> set = new TreeSet<String>(new MyComparator());
// 读取IP.txt文件;
String ipStr = null;
while ((ipStr = bufReader.readLine()) != null) {
set.add(ipStr.trim());
}
bufReader.close();
// 直接打印;
for (String str : set) {
System.out.println(str);
}
}
}
class MyComparator implements Comparator<String> {
@Override
public int compare(String o1, String o2) {
String[] strAr1 = o1.split("\\.");
String[] strAr2 = o2.split("\\.");
// 比较四个间区的Ip大小;
for (int i = 0; i < strAr1.length; i++) {
// 相等跳出,比下一个间区;
if (strAr1[i].equals(strAr2[i])) {
continue;
}
// 不相等,则可以确定顺序
Integer i1 = new Integer(strAr1[i]);
Integer i2 = new Integer(strAr2[i]);
return i1.compareTo(i2);
}
// IP完全相同,则不加入;可以改变0,就可以加入;
return 0;
}
} |