【题目描述】
创建一个学生类(Student),将学生信息(名字 name、年龄 age、语文成绩 chinese、数学成绩 math、英语成绩 english)保存到指定文件中,并判断文件中是否存在学生信息(反序列化),若存在则输出学生学习。
【代码实现】
学生类(Student):
class Student implements Serializable {
public String name;
public int chinese;
public int math;
public int english;
public Student(String name, int chinese, int math, int english) {
this.name = name;
this.chinese = chinese;
this.math = math;
this.english = english;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "学生姓名:" + name + "\n"
+ "学生语文成绩:" + chinese + "\n"
+ "学生数学成绩:" + math + "\n"
+ "学生英语成绩:" + english + "\n___________";
}
}
信息管理类(Information):
class Information {
public void saveInformation(String address, ArrayList<Student> student) {
for( Student save : student) {
File file = new File(address + "\\" + save.getName() + ".txt");
try {
if( file.createNewFile() ) {
try ( FileOutputStream out = new FileOutputStream(address + "\\" + save.getName() + ".txt") ) {
ObjectOutputStream oos = new ObjectOutputStream(out);
oos.writeObject(save);
out.close();
oos.close();
}
}
} catch (IOException e) {
throw new RuntimeException();
}
}
}
public void retrieveInformation( String address) {
File dictionary = new File(address);
if( dictionary.isDirectory() ) {
File[] student = dictionary.listFiles();
if( student != null ) {
for( File t : student) {
try (FileInputStream in = new FileInputStream(address + "\\" + t.getName())) {
ObjectInputStream oos = new ObjectInputStream(in);
try {
Student student1 = (Student) oos.readObject();
System.out.println(student1.toString());
} catch (ClassNotFoundException e) {
throw new ClassCastException("读取学生信息失败!!!");
}
in.close();
oos.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
else {
System.out.println("没有学生信息");
}
}
else {
System.out.println("指定路径不是一个目录");
}
}
}
我们在Information类中实现了两个方法,分别是 保存信息(saveInformation)方法 和 输出信息(retrieveInformation)方法。
主类:
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
// 输入学生人数
int number = s.nextInt();
// 输入学生信息
ArrayList<Student> student = new ArrayList<>();
for( int i = 0; i < number; i++) {
Student t = new Student( s.next(), s.nextInt(), s.nextInt(), s.nextInt());
student.add(t);
}
Information information = new Information();
System.out.println("输入保存地址!!!");
String address = s.next();
information.saveInformation(address, student);
information.retrieveInformation(address);
}
}
我们使用动态数组暂时存储学生信息,然后通过信息管理类(Information)中的 saveInformation()方法 将其传入到输入的指定路径中去,最后通过 retrieveInformation()方法 读取学生信息。
java字节流相关概念可看我主页 《深入了解java字节流:探索输入流与输出流》 文章。
java File类相关概念可看我主页 《Java File类代码示例》文章。
java对象序列化相关概念可看我主页《简单理解Java文件操作与对象序列化》 文章。