package com.bjsxt.IO;
import java.io.Serializable;
public class Stu implements Serializable {
private static final long serialVersionUID = 9040001675273134854L; //具备可序列化和反序列化的能力
private String name;
private int age;
public static String schoolName; //static 不会被序列化
transient String pwd; //transient 不会被序列化
public Stu() {
}
public Stu(String name, int age, String pwd) {
this.name = name;
this.age = age;
this.pwd = pwd;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", pwd=" + pwd +", schoolName="+schoolName+
'}';
}
}
Classes类
package com.bjsxt.IO;
import com.bjsxt.collection.Student;
import java.io.Serializable;
import java.util.ArrayList;
public class Classes implements Serializable {
private static final long serialVersionUID = -7097903749347750461L;
private String className;
private ArrayList<com.bjsxt.IO.Stu> al; //要将classes写入磁盘 那Student也得是可序列化和可反序列化的
public Classes(String className, ArrayList<Stu> al) {
this.className = className;
this.al = al;
}
public Classes() {
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public ArrayList<Stu> getAl() {
return al;
}
public void setAl(ArrayList<Stu> al) {
this.al = al;
}
@Override
public String toString() {
return "classes{" +
"className='" + className + '\'' +
", al=" + al +
'}';
}
}
读写
package com.bjsxt.IO;
import java.io.*;
import java.util.ArrayList;
public class TestObjectOutputStream3 {
public static void main(String[] args) {
write();
read();
}
//写对象
public static void write(){
//创建学生对象
ArrayList<Stu> al = new ArrayList<>();
Stu stu1 = new Stu("zhang",20,"123456");
Stu stu2 = new Stu("yang",22,"654321");
Stu stu3 = new Stu("chen",23,"888888");
al.add(stu1);
al.add(stu2);
al.add(stu3);
//创建班级对象
Classes cl = new Classes("one", al);
//创建对象输出流
ObjectOutputStream oos = null;
try {
oos = null;
oos = new ObjectOutputStream(new FileOutputStream("d:/java/classes.txt"));
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭流
if(oos!= null){
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//读取
public static void read(){
ObjectInputStream ois = null;
try {
ois = null;
ois = new ObjectInputStream(new FileInputStream("d:/java/classes.txt"));
Classes cl = (Classes)ois.readObject();
System.out.println(cl.getClassName()+"\t"+cl.getAl());
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if(ois!=null){
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
运行结果

查了一下说是EOFException是意外到达文件或流的末尾抛出的异常,解决方法有点没看懂。。看不出来52行哪里有问题。。第九行是调用read()。