package cn.edu.sdut.acm;
import java.io.*;
import java.util.*;
class Student implements Serializable{ // 让Student对象可序列化
String id;
String name;
String stuClass;
int age;
public Student(String id, String name, String stuClass, int age) {
super();
this.id = id;
this.name = name;
this.stuClass = stuClass;
this.age = age;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", age=" + age + ", class=" + stuClass + "]";
}
}
public class Main{
public static void main(String[] args) throws IOException, ClassNotFoundException {
Student stu1 = new Student("001", "Bob", "软件1805", 16); // 创建两个Student对象
Student stu2 = new Student("002", "Join", "软件1804", 18);
Student stuArray[] = new Student[2]; // 创建Student数组
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("\\javaDemo\\stu.dat")); // 创建输出流
ObjectInputStream is = new ObjectInputStream(new FileInputStream("\\javaDemo\\stu.dat")); // 创建输入流
stuArray[0] = stu1; // 对象放入数组
stuArray[1] = stu2;
os.writeObject(stuArray); // 将数组写入文件
Object obj = is.readObject(); // 从文件中获取对象
if (obj instanceof Student[]) { // 判断,并向上转型
Student[] stus = (Student[]) obj;
for (Student stu : stus) { // 迭代遍历输出
System.out.println(stu);
}
}
os.close(); // 关闭流
is.close();
}
}
标签:文件,String,读写,输入输出,age,Student,new,id,name From: https://www.cnblogs.com/sly-345/p/18607113