集合到文件写入操作(java)

实现效果
集合到文件写入操作(java)_第1张图片
学生类 Student

package ioStreamDemo;

public class Student {
    private String name;
    private Integer Chinese;
    private Integer math;
    public Student(){}
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getChinese() {
        return Chinese;
    }

    public void setChinese(int chinese) {
        Chinese = chinese;
    }

    public int getMath() {
        return math;
    }

    public void setMath(int math) {
        this.math = math;
    }
    public int getSum(){
        return this.Chinese+this.math;
    }
}

测试类

package ioStreamDemo;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Scanner;
import java.util.TreeSet;

public class SetFileDemo {
    public static void main(String[] args) throws IOException {
        BufferedWriter bw = new BufferedWriter(new FileWriter("55.txt"));
        TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                int num = o1.getSum()-o2.getSum();
                int num1 = num==0?o1.getChinese()-o2.getChinese():num;
                int num2 = num1==0?o1.getMath()-o2.getMath():num1;
                int num3 = num2==0?o1.getName().compareTo(o2.getName()):num2;
                return num3;
            }
        });
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入5此数据:");
        for (int i=0;i<5;i++){
            System.out.println("请输入学生姓名:");
            Student stu = new Student();
            String name = sc.next();
            stu.setName(name);
            System.out.println("请输入语文成绩:");
            int chinese = sc.nextInt();
            stu.setChinese(chinese);
            System.out.println("请输入数学成绩:");
            int math = sc.nextInt();
            stu.setMath(math);
            int sum = stu.getSum();
            ts.add(stu);
        }
        for (Student s:ts){
            StringBuilder sb = new StringBuilder();
            sb.append(s.getName()).append(",").append(s.getChinese()).append(",").append(s.getMath()).append(",").append(s.getSum());
            bw.write(sb.toString());  //toString
            bw.newLine();
            bw.flush();
        }
    }
}

你可能感兴趣的:(java)