`

根据文件内容排序

    博客分类:
  • Java
阅读更多
package cn.xbmu.lib.jfly.test;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;

/**
 * 文件intel.txt,内容如下:
 * 小王【空格】10000【回车】
 * 小强【空格】12345【回车】
 * 小张【空格】2342 【回车】
 * 小强【空格】1030 【回车】
 * 小周【空格】1020 【回车】
 * 小杨【空格】2342 【回车】
 * 请编写一程序从test.txt中读取数据,并按数字大小排序后写入另一文件sun.txt(写入格式同上)
 * @author JFly
 */
public class SortFileContentByNum {

    public static void main(String[] args) throws FileNotFoundException, IOException {
        BufferedReader br = new BufferedReader(new FileReader("C:/test.txt"));
        String line = null;
        int size = 0;
        ArrayList<String> al = new ArrayList<String>();
        while ((line = br.readLine()) != null) {
            if (!line.isEmpty()) {
                al.add(line);
                size++;
            }
        }
        br.close();
        
        String[] b = al.toArray(new String[size]);
        Arrays.sort(b, new Comparator<String>() {
             public int compare(String s1, String s2) {
                int i1 = 0;
                int i2 = 0;
                if (s1.matches(".+\\s+\\d+") && s2.matches(".+\\s+\\d+")) {
                    i1 = Integer.parseInt(s1.replaceAll("\\D", ""));
                    i2 = Integer.parseInt(s2.replaceAll("\\D", ""));
                }
                if(i1 == i2) {
                    String str1 = s1.replaceAll("\\d", "");
                    String str2 = s2.replaceAll("\\d", "");
                    return str1.compareTo(str2) > 0 ? -1 : 1;
                }
                return i1 < i2 ? -1 : 1;
            }
        });
        
        BufferedWriter bw = new BufferedWriter(new FileWriter("c:/result.txt"));
         for(String s : b) {
            bw.write(s);
            bw.write("\r");
        }
        bw.flush();
        bw.close();
    }
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics