import java.io.*;
import java.util.*;
/*
* 读取一个文件里边的所有学生成绩信息
* 按照成绩降序排序
* 写入另一个新的文件
*/
public class SortCopy {
private static List<Student> list =new ArrayList<Student>();
public static void main(String[] args) throws IOException {
//键盘录入.
BufferedReader bfr = new BufferedReader( new InputStreamReader(System.in));
File file = new File(bfr.readLine());
if(!file.exists()){
System.out.println("无效路径");
return;
}
getSourceFile(file);
sortList();
//file获取文件名
String name = file.getName();
name = "sort"+name;
String parent = file.getParent();
saveFile(new File(parent,name));
}
private static void getSourceFile(File sourceFile){
//读取源文件中每个学生的信息并存储在集合中。
BufferedReader bfr = null;
try{
bfr = new BufferedReader(new InputStreamReader(new FileInputStream(sourceFile)));
String line = null;
while((line = bfr.readLine())!=null){
line.trim();
String [] str = line.split(" +");
list.add(new Student(str[0],Integer.parseInt(str[1])));
}
sortList();
// System.out.println(list);
}catch(Exception e){
e.printStackTrace();
throw new RuntimeException("读取文件失败");
}
}
private static void sortList(){
//对集合中的元素进行排序。
Collections.sort(list,Collections.reverseOrder());
// System.out.println(list);
}
private static void saveFile(File targetFile){
//将排序后的集合存储在一个新的同名的文件中。
BufferedWriter bfw = null;
try{
bfw = new BufferedWriter(new FileWriter(targetFile));
for(Student a:list){
String name = (a.getName());
int sorce = a.getScore();
bfw.write(name+"\t"+sorce);
bfw.newLine();
bfw.flush();
}
}catch(Exception e){
e.printStackTrace();
throw new RuntimeException("复制文件失败");
}finally {
try{
if(bfw!=null)
bfw.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
}
public class Student implements Comparable<Student> {
private String name;
private int score;
public Student(String name, int score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public String toString(){
return name +"...."+ score;
}
@Override
public int compareTo(Student stu) {
int num = this.score - stu.score;
return num==0?this.name.compareTo(stu.name):num;
}
}
感觉这样的代码不是很简便,还请大神赐教!
|
|