前两天在JavaEye上看到了篇文章,作者在一家公司面试遇到了这个问题,感觉蛮有意思,自己回头写了下。
自己的接触Java有半年多了,由于是做Web开发的,大部分情况下用Java来操作数据库。对于文件的读写很少
用到,写起来比较生疏,简单的功能用了一个小时,代码写的相当笨拙,在这亮一下,希望大牛们给指点一二
最好给些现成的代码好学习下,将来要不找工作写出这种代码估计很难过关.
ps:文件的格式是
XXXX 数字\n
XXXX 数字\n
......
要求读出文件中的数据,按数字排序后写回到另一文件
- Java code
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=null; Iterator i=lsRecords.iterator(); while(i.hasNext()){ sLineData=(String)i.next(); sLineData=sLineData.replaceAll(":", " ")+"\n"; bufwriter.write(sLineData); } }catch(Exception ex){ throw ex; }finally{ try{ if(bufwriter!=null) bufwriter.close(); }catch(Exception ex){} } }}