对象序列化
作用:可以将对象以文件的形式保存到电脑上
·定义·
:将对象转换成可以通过二进制进行传输的二进制文件
序列化步骤
- 创建一个学生对象(保存姓名和id),实现序列化接口
implements Serializable //实现序列化接口
package ObjectStudent;
import java.io.Serializable;
public class Student implements Serializable{
private String name;
private Integer id;
public Student(String name, Integer id) {
super();
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Override
public String toString() {
return "Student [name=" + name + ", id=" + id + "]";
}
}
- 创建两个学生对象,然后将学生对象通过序列化流,保存到文件中
package ObjectStudent;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
public class Test {
public static void main(String[] args) {
Student stu1 = new Student("张三", 1);
Student stu2 = new Student("李四", 2);
OutputStream os = null;//创建一个字节流
ObjectOutputStream oos = null;
try {
os = new FileOutputStream("D:/aaaaaaaaa.txt");//需要保存的文件位置,如果没有文件他会给你自动生成一个
oos = new ObjectOutputStream(os);
oos.writeObject(stu1);//将对象stu1写到文件中
oos.writeObject(stu2);//将对象stu1写到文件中
oos.flush();//穿进去之后要刷新
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
oos.close();//释放流
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
对象反序列化
定义
:把我们通过序列化生成的二进制文件转换为我们的原对象(只是对象中的数据相同)
package ObjectStudent;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
public class InputStudent {
public static void inputStream() {
InputStream is = null;//字符流
ObjectInputStream ois = null;//Object流
File file = new File("D:/aaaaaaaaa.txt");//目标文件,就是你保存对象的文件
try {
is = new FileInputStream(file); //这个流用来传输file类
ois = new ObjectInputStream(is);
Object obj = null;
try {
while(true) {
obj = ois.readObject();
System.out.println(obj);
}
} catch (EOFException e) {
System.out.println("读取完毕");
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
ois.close();//释放流
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
然后在测试类中调用该方法就可以了
package ObjectStudent;
public class Test {
public static void main(String[] args) {
InputStudent.inputStream();
}
}