/*
*有五个学生,每个学生有3门课的成绩,定义一种比较直观的文本文件格式,
输入学生姓名和成绩,输入的格式:name,30,30,30从键盘输入以上数据(包括姓名,三门课成绩),
按总分数从高到低的顺序将学生信息存放在磁盘文件"stu.txt"中。
*
* 思路:
* 1.数据输入需要用到IO流
* 1.源和目的:
* 源:InputStream FileWriter
* 目的:OutputStream FileReader
* 2.是否为纯文本
* 是,源:FileWriter
* 目的:FileReader
* 3.明确设备:
* 源:键盘 system.in
* 目的:硬盘 file
* 4.额外功能:
* 需要对程序排序
* 高效,用bufferReader
*
* 2.有姓名,有成绩,可以使用Map集合进行存储,姓名做键,成绩做值
*
* 3.需要对总成绩进行比较,用map构造函数的comparetor比较器只能比较键的顺序;
* 所以要比较值的顺序,可将map转为Set集合,再转为List集合,用类 Collections中的
* static <T> void
sort(List<T> list, Comparator<? super T> c)
根据指定比较器产生的顺序对指定列表进行排序。
* 方法排序。
*
* 4.用IO流写到文件中。
*
*
*
* fr,41,64,82
ge,36,54,97
bew,63,54,97
bt,74,21,63
gt,32,28,69
hh,74,25,38
*
*/
public class StuIOText {
public static void main(String[] args) throws IOException {
// TODO 自动生成的方法存根
TreeMap<String, String> tm = ResultsTheInput();
System.out.println(tm);
List<Map.Entry<String, String>> sortList = valueSort(tm);
System.out.println(sortList);
writerReport(sortList);
}
public static void writerReport(List<Map.Entry<String, String>> sortList)
throws IOException {
BufferedWriter bw = new BufferedWriter(new FileWriter("sotValue.txt"));
for(Map.Entry<String, String> list : sortList){
bw.write(list.getKey() + ": " + list.getValue() + System.lineSeparator());
}
bw.close();
}
//重点注意:各个集合间的转换!!
public static List<Entry<String, String>> valueSort(TreeMap<String, String> tm) {
//将map集合转化为Set集合
Set<Map.Entry<String, String>> setMap = tm.entrySet();
//将Set集合再转化为List集合
List<Map.Entry<String, String>> listMap = new ArrayList<>(setMap);
//运用Collections类中sort方法,将list集合按指定的比较器进行排序
Collections.sort(listMap, new ValueCompare());
return listMap;
}
public static TreeMap<String, String> ResultsTheInput() throws IOException {
// TODO 自动生成的方法存根
int count = 0;
BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
TreeMap<String, String> tm = new TreeMap<String, String>();
String line = null;
String[] value = new String[5];
String[] key = new String[5];
while((line=br.readLine())!=null){
//以逗号为分隔符,将输入字符串分割为字符串
String[] str = line.split(",");
key[count] = str[0];
value[count] = str[1] + "," + str[2] + "," + str[3];
//以姓名为键,总成绩为值,输入到map集合中
tm.put(str[0], value[count]);
count++;
if(count == 5)
break;
}
return tm;
}
}
比较器代码:
public class ValueCompare implements Comparator<Map.Entry<String,String>> {
@Override
public int compare(Entry<String, String> o1, Entry<String, String> o2) {
// TODO 自动生成的方法存根
String[] str1 = o1.getValue().split(",");
String[] str2 = o2.getValue().split(",");
int[] result = new int[2];
//将字符串转换为Integer类型,然后进行求和运算
result[0] = Integer.valueOf(str1[0])+Integer.valueOf(str1[1])+Integer.valueOf(str1[2]);
result[1] = Integer.valueOf(str2[0])+Integer.valueOf(str2[1])+Integer.valueOf(str2[2]);
return result[0] - result[1];
}
//其他实现的接口方法省略
//-----------------------
}