[Java基础]对象(反)序列化流
Posted Wecccccccc
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Java基础]对象(反)序列化流相关的知识,希望对你有一定的参考价值。
对象序列化流:
代码如下:
package ObjectOutputStreamPack;
import java.io.Serializable;
public class Student implements Serializable {
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
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;
}
}
package ObjectOutputStreamPack;
import java.io.*;
public class ObjectOutputStreamDemo
{
public static void main(String[] args) throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:\\\\JavaDemo\\\\oos.txt"));
Student s = new Student("Tom",33);
oos.writeObject(s);
oos.close();
}
}
对象反序列化流:
代码如下:
package ObjectOutputStreamPack;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
public class ObjectInputStreamDemo {
public static void main(String[] args) throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:\\\\JavaDemo\\\\oos.txt"));
Object obj = ois.readObject();
Student s = (Student) obj;
System.out.println(s.getName()+","+s.getAge());
ois.close();
}
}
以上是关于[Java基础]对象(反)序列化流的主要内容,如果未能解决你的问题,请参考以下文章
java基础 序列化反序列化流 实现Serializable 接口 自动装载序列号到对象文本文件如修改不能反序列化对象文本,除非自定义long型常量 打印流
阶段1 语言基础+高级_1-3-Java语言高级_06-File类与IO流_09 序列化流_3_对象的反序列化流_ObjectInputStream