共计 2658 个字符,预计需要花费 7 分钟才能阅读完成。
把对象以流的办法,写入到文件中保留:写对象(对象的序列化)
对象中蕴含的不仅仅是字符,应用字节流
ObjectOutputStream(对象序列化流)
ObjectInputStream(对像反序列化流)
ObjectOutputStream 类
对象的序列化流
java.io.ObjectOutputStream extends OutputStream
把对象以流的模式写入到文件中保留
构造方法:
ObjectOutputStream(OutputStream out):创立写入指定 OutputStream 的 ObjectOutputStream
参数:OutputStream out:字节输入流
特有成员办法:
void writeObject(Object obj):将指定的对象写入 ObjectOutputStream
应用步骤
- 创立 ObjectOutputStream 对象,构造方法传递字节输入流
- 应用 ObjectOutputStream 对象中 writeObject 办法,把对象写入到文件中
- 开释资源
序列化和反序列化时,会抛出 NotSerializableException
要实现序列化和反序列化的类必须实现 Serializable 接口(仅起标记作用)
public class Person implements Serializable {
private String name;
private int age;
....
}
public static void main(String[] args) throws IOException {ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("E:\\A JI\\program\\java\\test-txt\\person.txt"));
oos.writeObject(new Person("hehe", 18));
oos.close();}
ObjectInputStream 类
对象的反序列化流
java.io.ObjectInputStream extends InputStream
把文件中保留的对象,以流的形式读取应用
构造方法:
ObjectInputStream(InputStream In):创立写入指定 InputStream 的 ObjectInputStream
参数:InputStream in:字节输出流
特有的成员办法:
Object readObject() 从 ObjectInputStream 读取对象
应用步骤
- 创立 ObjectInputStream 对象,构造方法传递字节输出流
- 应用 ObjectInputStream 对象中 readObject 办法,读取保留对象的文件
- 开释资源
- 应用读取的对象(打印)
readObject()申明会抛出 ClassNotFoundException(class 文件找不到异样)
反序列化前提:
**1. 类必须实现 Serializable 接口
2. 必须存在类对应的 class 文件 **
public static void main(String[] args) throws IOException, ClassNotFoundException {ObjectInputStream ois = new ObjectInputStream(new FileInputStream("E:\\A JI\\program\\java\\test-txt\\person.txt"));
Object o = ois.readObject();
ois.close();
System.out.println(o);
Person p = (Person)o;
System.out.println(p.getName() + p.getAge());
}
output:
Person{name='hehe', age=18}
hehe18
transient 关键字
被 transient 润饰的成员变量,不能被序列化
解决方案:
开发者本人定义一个序列号
private static final long serialVersionUID = 1L;
案例
序列化汇合
public static void main(String[] args) throws IOException, ClassNotFoundException {
// 定义存储 Person 对象的数组
ArrayList<Person> list = new ArrayList<>();
list.add(new Person("zz", 18));
list.add(new Person("qq", 19));
list.add(new Person("cc", 20));
// 存储 Person 对象到 ArrayList 数组中
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("E:\\A JI\\program\\java\\test-txt\\person12.txt"));
oos.writeObject(list);
// 读取文件中保留的汇合
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("E:\\A JI\\program\\java\\test-txt\\person12.txt"));
Object o = ois.readObject();
// 将 Object 类型汇合转换为 ArrayList 汇合
ArrayList<Person> list2 = (ArrayList<Person>) o;
for (Person person : list2) {System.out.println(person.getName() + " " + person.getAge());
}
}
output:zz 18
qq 19
cc 20
打印流
java.io.PrintStream extends OutputStream
特点:
- 只负责数据输入,不负责数据的读取
- 永远不会抛出 IOException
- 特有办法:print,println
构造方法:
PrintStream(File file):输入目的地是一个文件
PrintStream(OutputStream out):... 是一个字节输入流
PrintStream(String fileName):... 是一个文件门路
如果应用继承自父类的 write 办法写数据,查数据会查问编码表
如果应用本身特有的 print/println 办法写数据,写得数据原样输入