刚写出来的一道入学考试题,请大神们指教!
把以下IP存入一个txt文件,编写程序把这些IP按数值大小,从小到大排序并打印出来。
61.54.231.245
61.54.231.9
61.54.231.246
61.54.231.48
61.53.231.249
/*
* @throws IOException
*/
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("ip.txt")); //创建带缓冲区字符输入流
TreeSet<String> ts = new TreeSet<>(new Comparator<String>() { //创建treeset集合并带比较器
@Override
public int compare(String s1, String s2) {
s1 = s1.replaceAll("\\.", ""); //用空字符串代替代替字符串里面的.
s2 = s2.replaceAll("\\.", "");
int num = 1; //默认 s1>= s2;
if(Long.parseLong(s1) < Long.parseLong(s2)) {
num = -1;
}
return num;
}
});
String line = "";
while((line = br.readLine()) != null) { //读取文件数据
ts.add(line);
}
br.close(); //关闭流
for (String string : ts) { //遍历集合
System.out.println(string);
}
}
}
|
|