java 如何实现对文本记录的排序 例如 文本文件a.txt 中有以下记录 id,name ,age, 如何用Java实现从a文件读取记录,并按id 排序后输出到文本文件b.txt中。希望高手指教,要有详细测试通过的源码。 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 Pleas read this:http://blog.csdn.net/justinavril/archive/2008/09/13/2924557.aspx import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.util.Iterator;import java.util.Set;import java.util.TreeSet;public class Test { public static void main(String[] args) { Test t = new Test(); System.out.println(t.getData("a.txt")); t.writeFile(t.getData("a.txt"), "b.txt"); } public Set<Student> getData(String filename) { Set<Student> datas = new TreeSet<Student>(); // FileReader r = null; BufferedReader bf = null; try { bf = new BufferedReader(new FileReader(new File(filename)), 10240); String info = null; while ((info = bf.readLine()) != null) { String[] tem = info.split(","); Student s = new Student(tem[0], tem[1], Integer.parseInt(tem[2])); datas.add(s); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ try { bf.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return datas; } public boolean writeFile(Set< Student> datas,String filename){ if(datas == null || datas.size()<=0) return false; if(filename == null||filename.length()<=0) return false; BufferedWriter w = null; try { w = new BufferedWriter(new FileWriter(new File(filename),true)); Iterator< Student> it = datas.iterator(); while(it.hasNext()){ Student s = it.next(); String tmp = s.getId()+","+s.getName()+","+s.getAge()+"\n"; w.write(tmp); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ try { w.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return true; }}class Student implements Comparable<Student> { private String id; private String name; private int age; public int compareTo(Student o) { // TODO Auto-generated method stub if (id.compareTo(o.getId()) > 0) { return 1; } else if (id.compareTo(o.getId()) < 0) { return -1; } else { return 0; } } public Student(String id, String name, int age) { this.id = id; this.age = age; this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String toString(){ return "id="+id+","+"name="+name+","+"age="+age; }}a.txt:1006,zhangsan,201002,li si,301003,wangwu,251004,jack,261005,mary,20b.txt:1002,li si,301003,wangwu,251004,jack,261005,mary,201006,zhangsan,20 /* * Created on Sep 26,2008 * * Copyright by 布谷鸟 */package file;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.Iterator;import java.util.List;/** * * @Author <a href = "[email protected]">cuckoo</a> * @Time 11:20 * @Description 文本文件a.txt 中有以下记录 id,name ,age, 如何用Java实现从a文件读取记录,并按id 排序后输出到文本文件b.txt中 */public class SortFile { public static void main(String args[]){ SortFile sortFile = new SortFile(); String orginalPath = "c:/file.txt" ; List<Entity> list = sortFile.readFile(orginalPath); String newPath = "c:/result.txt" ; sortFile.writeFile(list,newPath); } /** * @Description 读取文件,并排序 * @return */ public List<Entity> readFile(String path){ File file = new File(path); List<Entity> list = new ArrayList<Entity>(); try { System.out.println("-------------开始读文件---------------"); BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file))); String readLine = null ; while((readLine = reader.readLine()) != null ){ String id = null ; String name = null ; String age = null ; readLine = readLine.trim(); id = readLine.substring(0, readLine.indexOf(" ")).trim(); readLine = readLine.substring(readLine.indexOf(" "),readLine.length()).trim(); name = readLine.substring(0,readLine.indexOf(" ")).trim(); age = readLine.substring(readLine.indexOf(" "),readLine.length()).trim(); Entity entity = new Entity(id,name,age); list.add(entity); } reader.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("----------------读文件结束-------------------"); Comparator comparator = new Comparator(){ public int compare(Object o1, Object o2) { // TODO Auto-generated method stub Entity p1 = (Entity) o1; Entity p2 = (Entity) o2; if (p1.getId() > p2.getId()) return 1; else return 0; } }; //排序 Collections.sort(list,comparator); return list ; } /** * @Description 将排序结果存到另一个文件中 * @param path */ public void writeFile(List<Entity> list,String path){ File file = new File(path); if(file.exists()){ file.delete(); } //换行 String lineSepeter = System.getProperty("line.separator"); try { BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(path))); Iterator<Entity> it = list.iterator(); String content = "" ; while(it.hasNext()){ Entity entity = it.next(); String readLine = entity.getId()+" "+entity.getName()+" "+entity.getAge()+lineSepeter; content+=readLine ; } writer.write(content); writer.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("写入文件完成"); } private class Entity{ public Entity(String id ,String name ,String age) { // TODO Auto-generated constructor stub try { _id = Integer.parseInt(id); _name = name; _age = Integer.parseInt(age); }catch (NumberFormatException e){ System.out.println("文件格式不正确"); } } public void setId(int id){ _id = id ; } public int getId(){ return _id ; } public void setName(String name){ _name = name ; } public String getName(){ return _name ; } public void setAge(int age){ _age = age ; } public int getAge(){ return _age ; } private int _id = 0 ; private String _name = null ; private int _age = 0 ; }}哎呀 慢了一步 -------------------------------------------------------Quietly through .... 看了楼主的提问,我借次补充个问题!,楼主不要介意!呵呵!要是先按照age排序,如果age相同再按姓名排序怎么做啊?我用的是两个比较器,还能有其他的方法吗? 江湖告急 如何修改java的虚拟机的内存大小 关于传参的问题 新手问题,swing中怎样将全选事件屏蔽 一个书上的习题 TreeMap中文排序求教! 不知道为什么 时间很紧,希望大侠来相助,(火急) 下面的代码能取出所有的主机IP地址么? Myeclipse 8.5只能启动tomcat5.5 启动tomcat6.0时老是出现“严重”错误 java.sql.SQLException: Incorrect string value: 开源框架好多啊,貌似spring,struts能能满足一般应用啊 客户端:多线程使用单个SOCKET发数
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;public class Test { public static void main(String[] args) {
Test t = new Test();
System.out.println(t.getData("a.txt"));
t.writeFile(t.getData("a.txt"), "b.txt");
} public Set<Student> getData(String filename) {
Set<Student> datas = new TreeSet<Student>();
// FileReader r = null;
BufferedReader bf = null;
try {
bf = new BufferedReader(new FileReader(new File(filename)), 10240);
String info = null;
while ((info = bf.readLine()) != null) {
String[] tem = info.split(",");
Student s = new Student(tem[0], tem[1], Integer.parseInt(tem[2]));
datas.add(s);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
bf.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return datas;
}
public boolean writeFile(Set< Student> datas,String filename){
if(datas == null || datas.size()<=0)
return false;
if(filename == null||filename.length()<=0)
return false;
BufferedWriter w = null;
try {
w = new BufferedWriter(new FileWriter(new File(filename),true));
Iterator< Student> it = datas.iterator();
while(it.hasNext()){
Student s = it.next();
String tmp = s.getId()+","+s.getName()+","+s.getAge()+"\n";
w.write(tmp);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
w.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return true;
}}class Student implements Comparable<Student> {
private String id; private String name; private int age; public int compareTo(Student o) {
// TODO Auto-generated method stub
if (id.compareTo(o.getId()) > 0) {
return 1;
} else if (id.compareTo(o.getId()) < 0) {
return -1;
} else {
return 0;
}
} public Student(String id, String name, int age) {
this.id = id;
this.age = age;
this.name = name;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public String getId() {
return id;
} public void setId(String id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
}
public String toString(){
return "id="+id+","+"name="+name+","+"age="+age;
}}a.txt:
1006,zhangsan,20
1002,li si,30
1003,wangwu,25
1004,jack,26
1005,mary,20b.txt:
1002,li si,30
1003,wangwu,25
1004,jack,26
1005,mary,20
1006,zhangsan,20
/*
* Created on Sep 26,2008
*
* Copyright by 布谷鸟
*/
package file;import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
/**
*
* @Author <a href = "[email protected]">cuckoo</a>
* @Time 11:20
* @Description 文本文件a.txt 中有以下记录 id,name ,age, 如何用Java实现从a文件读取记录,并按id 排序后输出到文本文件b.txt中
*/
public class SortFile { public static void main(String args[]){
SortFile sortFile = new SortFile();
String orginalPath = "c:/file.txt" ;
List<Entity> list = sortFile.readFile(orginalPath);
String newPath = "c:/result.txt" ;
sortFile.writeFile(list,newPath);
}
/**
* @Description 读取文件,并排序
* @return
*/
public List<Entity> readFile(String path){
File file = new File(path);
List<Entity> list = new ArrayList<Entity>();
try {
System.out.println("-------------开始读文件---------------");
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String readLine = null ;
while((readLine = reader.readLine()) != null ){
String id = null ;
String name = null ;
String age = null ;
readLine = readLine.trim();
id = readLine.substring(0, readLine.indexOf(" ")).trim();
readLine = readLine.substring(readLine.indexOf(" "),readLine.length()).trim();
name = readLine.substring(0,readLine.indexOf(" ")).trim();
age = readLine.substring(readLine.indexOf(" "),readLine.length()).trim();
Entity entity = new Entity(id,name,age);
list.add(entity);
}
reader.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("----------------读文件结束-------------------");
Comparator comparator = new Comparator(){
public int compare(Object o1, Object o2) {
// TODO Auto-generated method stub
Entity p1 = (Entity) o1;
Entity p2 = (Entity) o2;
if (p1.getId() > p2.getId())
return 1;
else
return 0;
}
};
//排序
Collections.sort(list,comparator);
return list ;
}
/**
* @Description 将排序结果存到另一个文件中
* @param path
*/
public void writeFile(List<Entity> list,String path){
File file = new File(path);
if(file.exists()){
file.delete();
}
//换行
String lineSepeter = System.getProperty("line.separator");
try {
BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(path)));
Iterator<Entity> it = list.iterator();
String content = "" ;
while(it.hasNext()){
Entity entity = it.next();
String readLine = entity.getId()+" "+entity.getName()+" "+entity.getAge()+lineSepeter;
content+=readLine ;
}
writer.write(content);
writer.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("写入文件完成");
}
private class Entity{
public Entity(String id ,String name ,String age) {
// TODO Auto-generated constructor stub
try {
_id = Integer.parseInt(id);
_name = name;
_age = Integer.parseInt(age);
}catch (NumberFormatException e){
System.out.println("文件格式不正确");
}
}
public void setId(int id){
_id = id ;
}
public int getId(){
return _id ;
}
public void setName(String name){
_name = name ;
}
public String getName(){
return _name ;
}
public void setAge(int age){
_age = age ;
}
public int getAge(){
return _age ;
}
private int _id = 0 ;
private String _name = null ;
private int _age = 0 ;
}
}哎呀 慢了一步
-------------------------------------------------------
Quietly through ....