本帖最后由 syw02014 于 2014-3-30 21:19 编辑
希望能帮到你:- package RIO_File;
- import java.io.FileWriter;
- import java.io.IOException;
- import java.util.Arrays;
- class RegexExcise {
- public static void main(String[] args) throws Exception {
- Excise_IP();//对ip地址排序
- }
- /*
- * ip地址排序。
- 61.54.231.245
- 61.54.231.9
- 61.54.231.246
- 61.54.231.48
- 61.53.231.249
- */
- public static void Excise_IP() throws Exception{
- FileWriter dest_ip=new FileWriter("C:\\Users\\Administrator\\Desktop\\ips.txt");
- StringBuffer sb=new StringBuffer();
- String str = "61.54.231.245 61.54.231.9 61.54.231.246 61.54.231.48 61.53.231.249";
- String sip=null;
- //1,为了让ip可以按照字符串顺序比较,只要让ip的每一段的位数相同,所以,补零,按照每一位所需做多0进行补充。
- 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
- //System.out.println(str);
- 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
- //System.out.println(str);
- String[] ips = str.split(" +"); //将ip地址切出。
- Arrays.sort(ips);//排序
- for(String ip : ips){
- sip=ip.replaceAll("0*(\\d+)", "$1");
- sb.append(sip+"\r\n");
- System.out.println(sip);//将原先补的0去掉
- }
-
- dest_ip.write(sb.toString());
- dest_ip.flush();
- }
- }
复制代码 程序在控制台上显示内容:
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
上面的程序用到了正则表达式,下面这个没有用到:
- import java.io.FileWriter;
- import java.io.IOException;
- class RegexExcise{
- static void main(String[] args) throws Exception
- {
-
- String[] str ={"61.54.231.245","61.54.231.9","61.54.231.246","61.54.231.48","61.53.231.249"};
- FileWriter dest_ip=new FileWriter("C:\\Users\\Administrator\\Desktop\\ipss.txt");
- StringBuffer sb=new StringBuffer();
- //冒泡排序
- for (int i = 0; i < str.length; i++){
- for (int j = 0; j < str.length - 1 - i; j++){
- if (ToNumber(str[j]) > ToNumber(str[j + 1])) {
- String strBu = str[j];
- str[j] = str[j + 1];
- str[j + 1] = strBu;
- }
- }
- }
- //输出IP地址排序后的结果
- for (int i = 0; i < str.length; i++){
- sb.append(str[i]+"\r\n");
- System.out.println(str[i]);
- }
- dest_ip.write(sb.toString());
- dest_ip.flush();
- }
- //Ip地址格式为:a.b.c.d每个数字范围在0~255之间,我们可以把它们看成一个四位的256进制数然后转换成十进制=a*256^3+b*256^2+c*256^1+d*256^0然后根据对应的十进制大小排序
- private static int ToNumber(String str) {
- String[] p = str.split(".");
- int sum = 0;
- for (int i = 0; i < p.length; i++)
- //每个IP地址累加和
- sum = sum * 256 + Integer.parseInt(p[i]);
- return sum;
- }
- }
复制代码 程序在控制台上显示内容:
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
|