日期:2014-05-20  浏览次数:20700 次

java IO问题:将一个txt文件去重并排序输出 帮忙看下下面代码有什么问题
 import java.util.*;  
import java.io.*;  
public class ResortByDel {  

public static class TimeComparator implements Comparator<TimeAndContent> {
public int compare(TimeAndContent o1, TimeAndContent o2) {
TimeAndContent timeContent1=new TimeAndContent();
TimeAndContent timeContent2=new TimeAndContent();
String time1=timeContent1.getTime();
String time2=timeContent2.getTime();
if(time1.compareTo(time2)==1){
return 1;
}else if(time1.compareTo(time2)==-1){
return -1;
}else{
return timeContent1.getContent().compareTo(timeContent2.getContent());
}


}
}      
public static void main(String[] args) throws Exception{
               FileReader fr=new FileReader("D:\\test1.txt");   
      BufferedReader br=new BufferedReader(fr);  
      List<TimeAndContent> contentList=new ArrayList<TimeAndContent>();  
      String line;   
      while((line=br.readLine())!=null) {    
      TimeAndContent timeContent=new TimeAndContent();    
      String[] row=line.split(" ",2); 
      timeContent.setTime(row[0]);
      timeContent.setContent(row[1]); 
      contentList.add(timeContent);          
      }  
 
 //去重
 Iterator<TimeAndContent> it=contentList.iterator(); 
 while(it.hasNext()){
 TimeAndContent a=it.next();
 if(contentList.contains(a)){
 it.remove();
 }else{
 contentList.add(a);
 }
 }
         //排序   
 Collections.sort(contentList , new TimeComparator());  
          StringBuilder builder = new StringBuilder();   
            for (int i = 0; i < contentList.size(); i++){  
             TimeAndContent timeContent=contentList.get(i);
                builder.append(timeContent.getTime());   
                builder.append(" ");   
                builder.append(timeContent.getContent());   
                builder.append("\r");   
              }     
             System.out.println(builder.toString());   
              write("D:\\test.txt", builder.toString());