该帖已经被评为新手帖
|
|
---|---|
作者 | 正文 |
发表时间:2009-01-08
最后修改:2009-01-08
我也来发表个,呵呵
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(); } }
|
|
返回顶楼 | |
发表时间:2009-01-09
还是觉得把Object放到ArrayList里面,用比较器拿出Objetc的属性来比较最舒服。
|
|
返回顶楼 | |
发表时间:2009-01-09
你这个帖子 怎么能发上来?
|
|
返回顶楼 | |
发表时间:2009-01-10
哎…… 这种还是保留在C语言的思想上。JavaSE 这么多的类库都不会用,用个arraylist包着hashmap不就得了。再匿名一个compararor接口不就得了。干嘛这么麻烦
|
|
返回顶楼 | |
发表时间:2009-01-10
spyker 写道 public class TestSort { public static void main(String[] args) { List<Integer> intList = new ArrayList<Integer>(); intList.add(123); intList.add(122223); intList.add(1233); intList.add(1234); intList.add(125); Integer[] intArr = intList.toArray(new Integer[intList.size()]); Arrays.sort(intArr); for (int i : intArr) { System.out.println(i); } } } jdk1.5下面的一个sort 呵呵 熟悉下api java.util.Collections.sort(intList); |
|
返回顶楼 | |
发表时间:2009-01-10
没颜色看着头痛。。
import com.j2se.file.MyIntComparator;//自定义比较器 import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.Iterator; import java.util.TreeMap; /*** *读文件test.txt内容(文件内容格式: 小王【空格】10000【回车】 * 小强【空格】12345【回车】 *并对该文件内容按存款数排序,然后将其写入另一文件内 * *****/ public class fileSort { /***** * 以行为单位读写文件 *@param fileName 源文件 *@param toFileName 目标文件 * ****/ public static void read_writeFile(String fileName,String toFileName){ File file = new File(fileName); BufferedReader reader=null; TreeMap<Integer,String> map = new TreeMap<Integer,String>(new MyIntComparator()); File toFile = new File(toFileName); PrintWriter writer = null; try{ System.out.println("------------------读文件开始-------------------------------"); System.out.println(); System.out.println("以行为单位读取文件内容,每次读取一整行"); reader = new BufferedReader(new FileReader(file)); String tempString = null; String[] ss = null; int line = 1; //一次读一行,直到读取为null while((tempString = reader.readLine()) != null){ //显示行号 System.out.println("line number is "+line+"::"+tempString); line++; ss = tempString.split(" "); int i = 0; String value = ss[i]; int key =Integer.parseInt(ss[i+1]); System.out.println("key is:"+key); System.out.println("value is:"+value); map.put(key, value); } System.out.println("------------------读文件结束-------------------------------"); System.out.println(); System.out.println("------------------写文件开始-------------------------------"); System.out.println("写文件开始:"+file.getAbsolutePath()); writer = new PrintWriter(new FileOutputStream(toFile)); if(map !=null){ Object key = null; Object value = null; // 使用迭代器遍历Map的键,根据键取值 Iterator it = map.keySet().iterator(); while (it.hasNext()){ key = it.next(); value = map.get(key); System.out.println("key is :"+key); System.out.println("vlaue is :"+value); //能写各种基本类型数据 writer.print(value+" "); writer.print(key+" "); //换行 writer.println(); //写入文件 writer.flush(); } System.out.println("写文件"+file.getAbsolutePath()+"成功!"); System.out.println("---------------------------写文件结束--------------------------"); } }catch(IOException e){ e.printStackTrace(); }finally{ if(reader != null){ try{ reader.close(); }catch(IOException e1){ e1.printStackTrace(); } } if(writer !=null){ writer.close(); } } } public static void main(String[] args){ String fileName = "D:/test.txt"; String toFileName = "D:/test1.txt"; fileSort.read_writeFile(fileName, toFileName); } } ----------------自定义比较器-------------------------------------- import java.util.Comparator; /** * 整数比较器,将整数按降序排列 */ class MyIntComparator implements Comparator{ /** * o1比o2大,返回-1;o1比o2小,返回1。 */ public int compare(Object o1, Object o2) { int i1 = ((Integer)o1).intValue(); int i2 = ((Integer)o2).intValue(); if (i1 < i2){ return 1; } if (i1 > i2){ return -1; } return 0; } } |
|
返回顶楼 | |
发表时间:2009-01-12
呵呵,几天没上来,又多了十几条评论,谢谢大家的参与了,
感觉看帖子确实能学到不少东西,提高了~ |
|
返回顶楼 | |
发表时间:2009-01-12
也写了一个,感觉读这种格式不严格数据应该用正则。第一次写这种程序,写web程序对文件读写部署,大家多指教
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){} } } } |
|
返回顶楼 | |
发表时间:2009-01-12
groovy的解法看着很爽啊
|
|
返回顶楼 | |
发表时间:2009-01-12
import java.io.*;
import java.util.*; public class TestSort{ public static void main(String[] args){ String s=""; try{ FileReader file=new FileReader("test1.txt"); BufferedReader buff=new BufferedReader(file); boolean eof=false; while (!eof){ String line= buff.readLine(); if (line==null) eof =true;else { s+=line; System.out.println(line); } } buff.close(); }catch (IOException e){e.printStackTrace();} //s..split(" "); System.out.println("ss=" + s ); StringTokenizer stoken = new StringTokenizer(s, " "); String ss[]= new String[stoken.countTokens()]; int i=0; // logger.info("**a.getArtkey()*******--nav pager-"+a.getArtkey()); while (stoken.hasMoreTokens()){ ss[i++]=stoken.nextToken(); } String[] people=new String[ss.length/2]; int[] value=new int[ss.length/2]; int[] value2=new int[ss.length/2]; for( i=0;i<ss.length/2;i++){ System.out.println("i="+i+"pep= "+ ss[i*2]); System.out.println("i="+i+"value = "+ ss[i*2+1]); people[i]=ss[i*2]; value[i]=Integer.parseInt(ss[2*i+1]); value2[i]=value[i]; } Arrays.sort(value2); try{ //FileWriter f=new FileWriter("test2.txt"); // BufferedWriter buff =new BufferedWriter(f); FileOutputStream f=new FileOutputStream("test2.txt"); DataOutputStream buff=new DataOutputStream(f); for( i=0;i<ss.length/2;i++){ int j=0; while (value2[i]!=value[j]) j++; System.out.println( "pep= "+ people[j]); System.out.println( "value = "+ value2[i]); buff. writeUTF( people[j] ); buff.writeUTF( String.valueOf(value2[i])); } buff.close(); }catch (IOException e){e.printStackTrace(); }} } 上机调试通过. |
|
返回顶楼 | |