黑马程序员技术交流社区

标题: 关于IP的问题,求大神帮忙! [打印本页]

作者: 北极雪871208    时间: 2014-3-30 19:52
标题: 关于IP的问题,求大神帮忙!
把以下IP存入一个txt文件,编写程序把这些IP按数值大小,从小到达排序并打印出来。
61.54.231.245
61.54.231.9
61.54.231.246
61.54.231.48
61.53.231.249
(版主顺便给俩技术分吧!多谢!)

作者: syw02014    时间: 2014-3-30 21:05
本帖最后由 syw02014 于 2014-3-30 21:19 编辑

希望能帮到你:
  1. package RIO_File;
  2. import java.io.FileWriter;
  3. import java.io.IOException;
  4. import java.util.Arrays;

  5. class RegexExcise {

  6.         public static void main(String[] args) throws Exception {
  7.                 Excise_IP();//对ip地址排序
  8.         }
  9.         /*
  10.         * ip地址排序。
  11.         61.54.231.245
  12.         61.54.231.9
  13.         61.54.231.246
  14.         61.54.231.48
  15.         61.53.231.249
  16.         */
  17.         public static void Excise_IP() throws Exception{
  18.                 FileWriter dest_ip=new FileWriter("C:\\Users\\Administrator\\Desktop\\ips.txt");
  19.                 StringBuffer sb=new StringBuffer();
  20.                 String str = "61.54.231.245 61.54.231.9 61.54.231.246 61.54.231.48 61.53.231.249";
  21.                 String sip=null;
  22.                 //1,为了让ip可以按照字符串顺序比较,只要让ip的每一段的位数相同,所以,补零,按照每一位所需做多0进行补充。
  23.                 str=str.replaceAll("(\\d+)","00$1");//每一段都加两个0061.0054.00231.00245 0061.0054.00231.009 0061.0054.00231.00246 0061.0054.00231.0048 0061.0053.00231.00249
  24.                 //System.out.println(str);
  25.                 str=str.replaceAll("0*(\\d{3})","$1");//然后每一段保留数字3位,061.054.231.245 061.054.231.009 061.054.231.246 061.054.231.048 061.053.231.249
  26.                 //System.out.println(str);
  27.                 String[] ips = str.split(" +");        //将ip地址切出。
  28.                 Arrays.sort(ips);//排序
  29.                 for(String ip : ips){
  30.                         sip=ip.replaceAll("0*(\\d+)", "$1");
  31.                         sb.append(sip+"\r\n");
  32.                         System.out.println(sip);//将原先补的0去掉
  33.                 }
  34.                
  35.                 dest_ip.write(sb.toString());
  36.                 dest_ip.flush();
  37.         }
  38. }
复制代码
程序在控制台上显示内容:
61.53.231.249
61.54.231.9
61.54.231.48
61.54.231.245
61.54.231.246
输出到ips.txt的内容:
61.53.231.249
61.54.231.9
61.54.231.48
61.54.231.245
61.54.231.246

上面的程序用到了正则表达式,下面这个没有用到:
  1. import java.io.FileWriter;
  2. import java.io.IOException;
  3. class RegexExcise{
  4.         static void main(String[] args) throws Exception
  5.         {
  6.            
  7.                 String[] str ={"61.54.231.245","61.54.231.9","61.54.231.246","61.54.231.48","61.53.231.249"};
  8.                 FileWriter dest_ip=new FileWriter("C:\\Users\\Administrator\\Desktop\\ipss.txt");
  9.                     StringBuffer sb=new StringBuffer();

  10.             //冒泡排序
  11.             for (int i = 0; i < str.length; i++){
  12.                 for (int j = 0; j < str.length - 1 - i; j++){
  13.                     if (ToNumber(str[j]) > ToNumber(str[j + 1])) {
  14.                             String strBu = str[j];
  15.                         str[j] = str[j + 1];
  16.                         str[j + 1] = strBu;
  17.                     }
  18.                 }
  19.             }

  20.             //输出IP地址排序后的结果
  21.             for (int i = 0; i < str.length; i++){
  22.                             sb.append(str[i]+"\r\n");
  23.                             System.out.println(str[i]);
  24.             }
  25.             dest_ip.write(sb.toString());
  26.                     dest_ip.flush();
  27.         }

  28.         //Ip地址格式为:a.b.c.d每个数字范围在0~255之间,我们可以把它们看成一个四位的256进制数然后转换成十进制=a*256^3+b*256^2+c*256^1+d*256^0然后根据对应的十进制大小排序
  29.         private static int ToNumber(String str) {
  30.                 String[] p = str.split(".");
  31.             int sum = 0;
  32.             for (int i = 0; i < p.length; i++)
  33.                 //每个IP地址累加和
  34.                 sum = sum * 256 + Integer.parseInt(p[i]);
  35.             return sum;
  36.         }
  37.     }
复制代码
程序在控制台上显示内容:
61.53.231.249
61.54.231.9
61.54.231.48
61.54.231.245
61.54.231.246
输出到ipss.txt的内容:
61.53.231.249
61.54.231.9
61.54.231.48
61.54.231.245
61.54.231.246




作者: stamSuper    时间: 2014-5-9 08:30
字符串不是有比较大小的方法么 ,直接用那个方法多好啊,没有必要这么麻烦

  1. public static String[] sortIp(String filePath) {
  2.                 File file = new File(filePath);
  3.                 BufferedReader reader =null;
  4.                 try {
  5.                         reader = new BufferedReader(new FileReader(file));
  6.                 } catch (FileNotFoundException e) {
  7.                         System.out.println("找不到文件,出现异常 ");
  8.                         return null;
  9.                 }
  10.                 String[] strArr;
  11.                 try {
  12.                         String ip = "";
  13.                         //用于保存 从文件中读取出来的的 ip 值
  14.                         List<String> strList = new ArrayList<String>();
  15.                         while(( ip = reader.readLine()) != null){
  16.                                 strList.add(ip);
  17.                         }
  18.                         //因为 数组的排序方法 需要使用  字符串数组进行比较 ,所以从新创建一个这样的数组 保存
  19.                         strArr = new String[strList.size()];
  20.                         strList.toArray(strArr);
  21.                         ///用Arrays 的静态方法  对数组中的元素进行排序
  22.                         sort(strArr);
  23.                         //返回排序后的结果
  24.                         return strArr;
  25.                 } catch (IOException e) {
  26.                         System.out.println("操作文件流出现异常");
  27.                 }finally{
  28.                         try {
  29.                                 if(reader != null)
  30.                                         reader.close();
  31.                         } catch (IOException e) {
  32.                                 System.out.println("关闭流异常");
  33.                         }
  34.                 }
  35.                 return null;
  36.         }
复制代码

  1. /**
  2.          * 对字符串数据进行排序,当然也有其他的方法,但都比较麻烦
  3.          * 我说下我的思路吧:
  4.          * 迭代字符串数组,也需要比较 字符串大小,然后重新排序
  5.          * @param strArr
  6.          */
  7.         private static void sort(String [] strArr){
  8.                 Arrays.sort(strArr,new Comparator<String>() {
  9.                         @Override
  10.                         public int compare(String str1, String str2) {
  11.                                 return str1.compareTo(str2);
  12.                         }
  13.                 });
  14.         }
复制代码

作者: code2014    时间: 2014-5-12 19:12
学习~~~~
作者: wuhyoung    时间: 2014-5-23 08:33
学习的。。
作者: hero112200    时间: 2014-6-24 22:43
学习一下……
作者: 坏男孩    时间: 2014-6-30 11:03
stamSuper 发表于 2014-5-9 08:30
字符串不是有比较大小的方法么 ,直接用那个方法多好啊,没有必要这么麻烦

哥们,你这个第45行报错了。。。
sort(strArr);
错误:The method sortIp(String) in the type Test_07 is not applicable for the arguments (String[])
应该怎么处理?
作者: 坏男孩    时间: 2014-6-30 20:51
syw02014 发表于 2014-3-30 21:05
希望能帮到你:程序在控制台上显示内容:
61.53.231.249
61.54.231.9

为什么上面这个编译后是没有排序的呢?
作者: 彭旋宇    时间: 2014-7-2 01:47
来看看{:3_46:}
作者: 帆~    时间: 2014-7-8 11:05
嗖嘎~~~   领悟中
作者: lucky_man    时间: 2014-7-12 02:22
楼上写的代码是不是有问题呀
作者: 为爱编程    时间: 2014-7-21 16:13
syw02014 发表于 2014-3-30 21:05
希望能帮到你:程序在控制台上显示内容:
61.53.231.249
61.54.231.9

大哥你这个打印结果,顺序没变??。。
作者: 沟门大杏    时间: 2014-8-6 15:41
厉害。这里的人好厉害
作者: 未名以律    时间: 2014-8-10 00:40
学习学习
作者: 陈新海1    时间: 2014-8-19 10:07
stamSuper 发表于 2014-5-9 08:30
字符串不是有比较大小的方法么 ,直接用那个方法多好啊,没有必要这么麻烦

全是错误你还加分,呵呵呵
作者: 姜浩    时间: 2014-9-21 12:16
syw02014 发表于 2014-3-30 21:05
希望能帮到你:程序在控制台上显示内容:
61.53.231.249
61.54.231.9

String[] p = str.split(".");
在运行时不会报错,但是会出现问题。
split();接收的是正则表达式。"."表示匹配任意字符。这样的话p.length=0。
根本不会进入for循环得不到sum的值,进而导致比较无效果。

改成String[] p = str.split("\\.");
作者: wujiemin    时间: 2014-10-7 15:39
这些都太麻烦了,直接利用set

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;
        }
}
作者: 高鹏飞    时间: 2014-10-22 08:44
本帖最后由 高鹏飞 于 2014-10-22 08:47 编辑
  1. public class Test8 {

  2.         public static void main(String[] args){
  3.                
  4.                 //调用IP排序方法
  5.                 sortIP(new File("F:\\ip.txt"));
  6.                
  7.         }

  8.         private static void sortIP(File file) {
  9.                
  10.                 //创建文件读取流
  11.                 BufferedReader br = null;
  12.                 try {
  13.                        
  14.                         br = new BufferedReader(new FileReader(file));
  15.                        
  16.                         //定义一个变量
  17.                         String line = null;
  18.                         //创建一个集合用来存储从文件读取到的IP
  19.                         List<String> list = new ArrayList<String>();
  20.                         while ((line=br.readLine())!=null) {
  21.                                 //先给读取到的每一个IP地址各段前补零
  22.                                 line = line.replaceAll("(\\d+)", "00$1");
  23.                                 //再取IP地址各段的后三位
  24.                                 line = line.replaceAll("0*(\\d{3})", "$1");
  25.                                 //将读取并经过正则表达式处理后的IP添加到list集合中
  26.                                 list.add(line);
  27.                         }
  28.                         //使用Collections的sort方法对其自然排序
  29.                         Collections.sort(list);
  30.                         //遍历集合打印输出排序后的IP地址
  31.                         for (String li : list) {
  32.                                 System.out.println(li.replaceAll("0*(\\d+)", "$1"));//使用正则表达式,将开始补全的0去掉
  33.                         }
  34.                 } catch (Exception e) {
  35.                        
  36.                 }finally{//关闭流
  37.                         if (br != null) {
  38.                                 try {
  39.                                         br.close();
  40.                                 } catch (IOException e) {
  41.                                        
  42.                                         throw new RuntimeException("关闭失败!");
  43.                                 }
  44.                         }
  45.                 }
  46.         }
  47. }
复制代码


作者: 高鹏飞    时间: 2014-10-22 08:47
打印结果:
61.53.231.249
61.54.231.9
61.54.231.48
61.54.231.245
61.54.231.246
作者: 齐宁宁    时间: 2014-10-23 08:16
来看看!
作者: 禾青青    时间: 2014-12-19 22:52

每天都来看一看

作者: 齐弦    时间: 2015-1-13 21:52
来借鉴一下
作者: __残梦、    时间: 2015-1-23 21:49
嘿嘿嘿嘿嘿嘿
作者: rehan    时间: 2015-2-22 16:10
。。。。。。。。。。。。。。。
作者: rehan    时间: 2015-2-22 16:46
有点难啊,怎么做???
作者: rehan    时间: 2015-2-22 21:48
syw02014 发表于 2014-3-30 21:05
希望能帮到你:程序在控制台上显示内容:
61.53.231.249
61.54.231.9

你的方法是错误的,控制台上的顺序一点没变!
作者: long_yihuan    时间: 2015-4-14 16:47
学习了。。
作者: 12300123    时间: 2015-5-5 22:29
wujiemin 发表于 2014-10-7 15:39
这些都太麻烦了,直接利用set

public class Test06 {

给力,给力。
作者: 一口老郭    时间: 2015-6-24 21:36
感觉好复杂的样子啊
作者: 15383016390    时间: 2015-7-3 16:53
stamSuper 发表于 2014-5-9 08:30
字符串不是有比较大小的方法么 ,直接用那个方法多好啊,没有必要这么麻烦

貌似字符串比较的话9会比236大,实现不了按数字比较,楼上那位加0的方法比较好
作者: 豪豪真是好    时间: 2015-11-23 11:11
/* 1.将IP的每一段都前面补两个0 2.将每一端都变成3位 //割成四段的IP 3.将其从大到小排列 4.将前面多余的0去掉 */ import java.util.*; import java.io.*; class RuXue1  {         public static void main(String[] args) throws Exception         {                 //System.out.println("Hello World!");                 IpSort();         }         public static void IpSort()throws Exception         {                 BufferedReader br=new BufferedReader(new FileReader("ruxue1.txt"));                 String line=null;                 StringBuffer sb=new StringBuffer();                 while ((line=br.readLine())!=null)                 {              sb.append(line+" ");                  }                   String str=sb.toString();                 //System.out.println(str);                                          //"61.54.231.245 61.54.231.9 61.54.231.246 61.54.231.48 61.53.231.249";                 //1.将IP的每一段都前面补两个0                 str=str.replaceAll("(\\d+)","00$1");                 //2.将每一端都变成3位                 str=str.replaceAll("0*(\\d{3})","$1");                 //割成四段的IP                 String[] s=str.split(" ");         //3.将其从大到小排列                 TreeSet<String> tree=new TreeSet<String>();                 for (String st:s)                 {                         tree.add(st);                 }                 for (String st:tree)                 {                         st=st.replaceAll("0*(\\d+)","$1");                         //打印字符串                         //4.将前面多余的0去掉                     System.out.println(st);                 }                           br.close();         } }
作者: 744919632    时间: 2015-12-18 15:05
看了半天,没有懂。
作者: doglovely    时间: 2016-3-7 22:57
我也不会这个,没有思路!
作者: 看好时机向前冲    时间: 2016-3-19 12:44
66666666666666




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2