题目描述:
1、采用对象输入输出流 2、自定义文件,存放某班级学生期末各科考试原始成绩 3、读取上述原始成绩文件,采用比较器按照某门课程分数高低排序
代码实现如下所示
代码语言:javascript复制package testOne;
import java.io.Serializable;
public class Student implements Serializable{
private String Sid;
private String Sname;
private String Cname;
private int Grade;
public Student(String sid, String sname, String cname, int grade) {
super();
Sid = sid;
Sname = sname;
Cname = cname;
Grade = grade;
}
public String getSid() {
return Sid;
}
public void setSid(String sid) {
Sid = sid;
}
public String getSname() {
return Sname;
}
public void setSname(String sname) {
Sname = sname;
}
public String getCname() {
return Cname;
}
public void setCname(String cname) {
Cname = cname;
}
public int getGrade() {
return Grade;
}
public void setGrade(int grade) {
Grade = grade;
}
@Override
public String toString() {
return "[学号=" Sid ", 姓名=" Sname ", 课程=" Cname ", 成绩=" Grade "]";
}
}
package testOne;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
public class FileUtil {
public void saveStudent(ArrayList<Student>students) {
try (ObjectOutputStream obs=new ObjectOutputStream(new FileOutputStream("Student.txt",true))){
for(Student stu:students) {
if(stu!=null) {
obs.writeObject(stu);
obs.flush();
}
}
obs.writeObject(null);
obs.flush();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public ArrayList<Student> readStudent(){
ArrayList<Student>students1=new ArrayList<>();
try (ObjectInputStream ois=new ObjectInputStream(new FileInputStream("Student.txt"))){
Student student;
while((student=(Student) ois.readObject())!=null) {
students1.add(student);
}
ois.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return students1;
}
}
package testOne;
import java.util.ArrayList;
import java.util.Comparator;
public class Test {
public static void main(String[] args) {
// TODO 自动生成的方法存根
FileUtil fileUtil1=new FileUtil();
ArrayList<Student>students=new ArrayList<>();
System.out.println("开始存学生信息");
for(int i=0;i<10;i ) {
if(i%2==0) {
students.add(new Student("1210" i, "张" i, "java程序设计", 70 2*i));
} else {
students.add(new Student("3211" i, "张" i, "java程序设计", 70-i));
}
}
fileUtil1.saveStudent(students);
for(Student stu:students) {
System.out.println(stu); } System.out.println("根据成绩排序");
FileUtil fileUtil2=new FileUtil();
ArrayList<Student>students2=fileUtil2.readStudent();
students2.sort(new Comparator<Student>() {
public int compare(Student stu1,Student stu2) {
int num=-(stu1.getGrade()-stu2.getGrade());
int num1=num==0?stu1.getSname().compareTo(stu2.getSname()):num;
return num1;
}
});
int count=0,j=1;
for(Student stu1:students2) {
if(stu1.getGrade()<70) {
count ;
}
System.out.println("学生" j stu1);
j ;
}
System.out.println("有" count "名学生成绩低于70分");
}
}