package com.itheima;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class Test6 {
/**
* 把以下IP存入一个txt文件,编写程序把这些IP按数值大小,从小到排序并打印出来。
* 61.54.231.245
* 61.54.231.9
* 61.54.231.246
* 61.54.231.48
* 61.53.231.249
* @throws FileNotFoundException
*/
static List<List<Integer>> list=new ArrayList<List<Integer>>();
//使用TreeSet进行排序
static Set<String> set=new TreeSet<String>();
public static void main(String[] args)
{
try {
//读取文件
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(new FileInputStream("ip.txt")));
boolean flag=true;
System.out.println("排序前:");
while(flag)
{
//读取每一行的数据
String buffer=bufferedReader.readLine();
if(buffer==null)
{
flag=false;
}else
{
syso(buffer);
}
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println();
System.out.println("排序后:");
//获取set的迭代器
Iterator<String> iterator=set.iterator();
while(iterator.hasNext())
{
String ip=iterator.next();
String[] arr=ip.split("\\.");
for (int i = 0; i < arr.length; i++) {
if(arr[i].startsWith("00"))
{
String str=arr[i].substring(0, 2);
arr[i]=arr[i].replace(str, "");
}else if(arr[i].startsWith("0"))
{
String str=arr[i].substring(0, 1);
arr[i]=arr[i].replace(str, "");
}
}
StringBuffer buffer2=new StringBuffer();
for (int i = 0; i < arr.length; i++) {
buffer2.append(arr[i]+".");
}
//删除最后一位多余的点
buffer2.replace(buffer2.length()-1, buffer2.length(), "");
System.out.println(buffer2.toString());
}
}
public static void syso(String buffer)
{
System.out.println(buffer);
//分割每一位
String[] sub=buffer.split("\\.");
//判断是否每一位是否够三位数,不够的在前面补0
for (int i = 0; i < sub.length; i++) {
if(sub[i].length()<3 && sub[i].length()>0)
{
switch (sub[i].length()) {
case 1:
sub[i]="00"+sub[i];
break;
case 2:
sub[i]="0"+sub[i];
break;
}
}
}
//对分割的字符进行处理
StringBuffer buffer2 = getIP(sub);
//把补零的字符串IP添加到TreetSet中
set.add(buffer2.toString());
}
public static StringBuffer getIP(String[] sub) {
StringBuffer buffer2=new StringBuffer();
//为每一位数的最后加上点
for (int i = 0; i < sub.length; i++) {
buffer2.append(sub[i]+".");
}
//删除最后一位多余的点
buffer2.replace(buffer2.length()-1, buffer2.length(), "");
return buffer2;
}
}
|
|