import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
/**
*
* 把以下IP存入一个txt文件,编写程序把这些IP按数值大小,从小到大排序并打印出来。
61.54.231.245
61.54.231.9
61.54.231.246
61.54.231.48
61.53.231.249
*
*
*
*
* @author perry
*
*/
public class Test8 {
public static void main(String[] args) throws IOException {
//创建录入流,把数据录入到指定文档
BufferedWriter bw = new BufferedWriter(new FileWriter("ip.txt"));
bw.write("61.54.231.245");
bw.newLine();
bw.write("61.53.231.249");
bw.newLine();
bw.write("61.54.231.246");
bw.newLine();
bw.write("61.54.231.48");
bw.newLine();
bw.write("61.54.231.9");
bw.flush();
bw.close();
//读取文档数据,添加到数组中去
BufferedReader br = new BufferedReader(new FileReader("ip.txt"));
ArrayList<String> al = new ArrayList<String>();
String line = null;
while ((line=br.readLine())!=null) {
al.add(line);
}
br.close();
//冒泡法,对数进行排序
for (int i = 0; i < al.size()-1; i++) {
for (int j = 0; j < al.size()-i-1; j++) {
//调用数值判断函数getsum,对数值的大小进行判断。
if (getSum(al.get(j))>getSum(al.get(j+1))) {
String str = al.get(j);
al.set(j, al.get(j+1));
al.set(j+1, str);
}
}
}
//增强for打印输出
for (String a : al) {
System.out.println(a);
}
}
//getSum 函数,获取ip值的实际数值大小,并且返回。
public static int getSum(String s){
String[] p = s.split("\\.");
int sum = 0;
for (int i = 0; i < p.length; i++) {
sum = sum*256+Integer.parseInt(p[i]);
}
return sum;
}
} |