日期:2014-05-18 浏览次数:20747 次
package com.saturday; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ReadTxt { public static void main(String args[]){ try{ List lsRecords=readData("D:/Data.txt"); sortRecord(lsRecords,"asc"); writeData(lsRecords); }catch(FileNotFoundException ex){ System.out.println("无法读取数据文件!"); }catch(Exception ex){ System.out.println(ex.getMessage()); } } public static List readData(String sFilePath) throws Exception{ BufferedReader bufreader=null; List lsRecords=new ArrayList(); try{ StringBuffer sbData=new StringBuffer(); String sLineData=null; bufreader=new BufferedReader(new FileReader(sFilePath)); Pattern p=Pattern.compile( "^\\s*(.*?)\\s+(\\d+)\\s*$", Pattern.MULTILINE); while((sLineData=bufreader.readLine())!=null){ sbData.append(sLineData+"\n"); } Matcher m=p.matcher(sbData); while(m.find()){ lsRecords.add(m.group(1)+":"+m.group(2)); } }catch(Exception ex){ throw ex; }finally{ try{ if(bufreader!=null) bufreader.close(); }catch(Exception ex){} } return lsRecords; } public static void sortRecord(List lsRecords,String sSortSty){ Comparator AscCmp=new Comparator(){ public int compare(Object o1,Object o2){ String str1=(String)o1; String str2=(String)o2; int int1=Integer.parseInt( str1.substring(str1.indexOf(':')+1)); int int2=Integer.parseInt( str2.substring(str2.indexOf(':')+1)); return int1<int2?-1:1; } }; Comparator DesCmp=new Comparator(){ public int compare(Object o1,Object o2){ String str1=(String)o1; String str2=(String)o2; int int1=Integer.parseInt( str1.substring(str1.indexOf(':')+1)); int int2=Integer.parseInt( str2.substring(str2.indexOf(':')+1)); return int1<int2?1:-1; } }; if(sSortSty.equals("des")) Collections.sort(lsRecords,DesCmp); else Collections.sort(lsRecords,AscCmp); } public static void writeData(List lsRecords) throws Exception{ BufferedWriter bufwriter=null; try{ bufwriter=new BufferedWriter(new FileWriter("D:/SortedData.txt")); String sLineData=nu