3. 解决方法:
????????把true删掉即可
4. 可执行的源码:
package com.objectStream;
import java.io.*;
public class ObjectOutputStreamExample {
public static void main(String[] args) throws Exception {
// 创建一个对象输出流
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("C:\\ZProject\\Java\\JavaBase\\test\\src\\com\\objectStream\\data.txt"));
// 创建两个对象
Student student1 = new Student("张小蓝", "永远的爱", "dushangxilou", 23);
Student student2 = new Student("李晓清", "消融的雪", "xifengdiaobishu", 15);
Student student3 = new Student("顾美琪", "寂静的宇宙", "wangjintianyalu", 15);
Student student4 = new Student("陈佳佳", "温暖的阳关", "denghuolanshanchu", 15);
// 对象序列化
objectOutputStream.writeObject(student1);
objectOutputStream.writeObject(student2);
objectOutputStream.writeObject(student3);
objectOutputStream.writeObject(student4);
// 关闭流文件
objectOutputStream.close();
// 创建对象输入流
FileInputStream fn = new FileInputStream("C:\\ZProject\\Java\\JavaBase\\test\\src\\com\\objectStream\\data.txt");
ObjectInputStream inputStream = new ObjectInputStream(fn);
Student s;
// 判断文件字节流是否大于0,文件中存在内容,小于0表示文件中不存在内容, 循环反序列化每个文件
while (fn.available() > 0){
// 将对象反序列化
s = (Student) inputStream.readObject();
System.out.println(s );
}
// 关闭流文件
inputStream.close();
fn.close();
}
}
package com.objectStream;
import java.io.Serializable;
public class Student implements Serializable {
private String name;
private String loginName;
private String passWord;
private int age;
public Student() {
}
public Student(String name, String loginName, String passWord, int age) {
this.name = name;
this.loginName = loginName;
this.passWord = passWord;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", loginName='" + loginName + '\'' +
", passWord='" + passWord + '\'' +
", age=" + age +
'}';
}
}
5. 结果: