- /*
- * 6、 把以下IP存入一个txt文件,编写程序把这些IP按数值大小,从小到达排序并打印出来。
- *
- * 61.54.231.245
- * 61.54.231.9
- * 61.54.231.246
- * 61.54.231.48
- * 61.53.231.249
- *
- * */
- public class Test6 {
-
- public static void main(String[] args){
- //存放IP地址的相对路径
- String str = ".\\src\\com\\itheima\\IP.txt";
- //把IP地址以字符串的形式作为参数
- List<String> list = printIP(str);
- //把返回的ArrayLst的对象 list用自定义的比较器Mycomparator排序
- Collections.sort(list,new Mycomparator());
- //用迭代器把比较后的结果打印到控制台
- Iterator<String> orderit = list.iterator();
- while (orderit.hasNext()) {
- System.out.println(orderit.next());
- }
- }
- private static List<String> printIP(String str) {
- //因为是纯文本文档此处可以用字符流,创建字符流缓冲对象,提高效率
- BufferedReader bufr = null;
- //创建ArrayList对象,用于存储Ip地址
- List<String> list = new ArrayList<String>();
- try {
- //创建字符读取流加入缓存
- bufr=new BufferedReader(new FileReader(str));
- //读入的一行字符
- String line=null;
- while((line=bufr.readLine())!=null){
- //每读取一行就存入list集合中
- list.add(line);
- }
-
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- //字符串数组
-
- try {
- if(bufr != null){
- bufr.close();
- }
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return list;
- }
-
-
- }
- class Mycomparator implements Comparator<String>{
- @Override
- public int compare(String s1, String s2) {
- //创建两个数组,用于存储切割后的IP
- String[] arr1 = s1.split("\\.");
- String[] arr2 = s2.split("\\.");
- //定义两个用于存储IP地址计算后的Long值对象,因为数据比较大,超出了int的范围
- long num1 = 0;
- long num2 = 0;
-
- for (int i = 0; i < arr1.length; i++) {
- //因为每一段IP的最大值是256,每一段乘以256的3-i的次方,方便下面的比较
- num1 = (long) (num1 + Integer.parseInt(arr1[i])*Math.pow(256,(3-i)));
- }
- for (int i = 0; i < arr2.length; i++) {
- //因为每一段IP的最大值是256,每一段乘以256的3-i的次方,方便下面的比较
- num2 = (long) (num2 + Integer.parseInt(arr2[i])*Math.pow(256,(3-i)));
- }
- //因为 num1-num2 的运算结果可能会超出int的范围,所以不能直接返回 num1-num2,最好先判断再返回1,-1或者0
- if(num1 - num2 > 0 ){
- return 1;
- }else if(num1 - num2 < 0 ){
- return -1;
- }
- return 0;
- }
-
- }
复制代码
|
|