A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 黑子 中级黑马   /  2014-6-18 14:57  /  754 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

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;
}

}

感觉这样的代码不是很简便,还请大神赐教!

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马