- import java.io.BufferedWriter;
- import java.io.FileWriter;
- import java.io.IOException;
- import java.util.Arrays;
- /**
- * 3. 把以下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 IpSort {
- String[] str1;
- public static void main(String[] args) {
- // 创建类对象
- IpSortTest ipst = new IpSortTest();
- // 调用类方法
- ipst.IpSortDemo();
- ipst.writerDemo();
- }
- }
- class IpSortTest {
- // 将IP写入IP.txt文件
- String str = "61.54.231.245 61.54.231.9 61.54.231.246 61.54.231.48 61.53.231.249";
- public void IpSortDemo() {
- // 声明StringBuffer容器
- StringBuffer sb = new StringBuffer();
- // 将由IP地址组成的字符串加上空格标记存入到str中
- String s4 = null;
- // 根据空格分割字符串
- String[] s = str.split(" ");
- // 遍历字符串数组
- for (String string : s) {
- String s1 = string;
- String s2;
- // 切割每个IP最后一个点后的字符
- s2 = s1.substring(s1.lastIndexOf(".") + 1);
- // System.out.println(s1);
- // 切割每个IP最后一个之前的字符
- String s3 = s1.substring(0, s1.lastIndexOf(".") - 1);
- // System.out.println(s3);
- // 判断切割出来的字符串,在其前补零
- if (s2.length() == 2) {
- s2 = "0" + s2;
- // System.out.println(s1);
- } else if (s2.length() == 1) {
- s2 = "00" + s2;
- // System.out.println(s1);
- }
- // 将字符串前后拼接起来
- s4 = s3 + "." + s2;
- // System.out.println(s4);
- // 用StringBuffer将拼接后的字符串接收
- sb.append(s4 + " ");
- // System.out.println(str1);
- }
- // 切割sb并加入数组
- String[] str1 = sb.toString().split(" ");
- // 排序
- Arrays.sort(str1);
- for (String str2 : str1) {
- // 用空字符替换IP中所有零
- String str3 = str2.replace("0", "");
- System.out.println(str3);
- }
- }
- public void writerDemo() {
- // 创建字符流对象
- // FileWriter fw = null;
- BufferedWriter bw = null;
- try {
- FileWriter fw = new FileWriter("d:\\IP.txt");
- // 将需要提高效率的流对象作为参数传递给缓冲区
- bw = new BufferedWriter(fw);
- bw.write(str);
- // 刷新
- bw.flush();
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- bw.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
复制代码 |
|