标签:机制 main puts 类型 小明 zab try 使用 进制
序列化是指把一个Java对象变成二进制内容byte[]
try(ObjectOutputStream output = new ObjectOutputStream(...)){
output.writeObject(new Person("小明"));
output.writeObject(new Person("小红"));
}
反序列化是指把一个二进制内容(byte[])变成Java对象
try(ObjectInputStream input = new ObjectInputStream(...)){
Object p1 = input.readObject();//使用readObject()获取Object对象
Person p2 = (Person) input.readObject();//如果读取的Person类型,需要强制转型
}
readObject()可能抛出的异常:
反序列化由JVM直接构造出Java对西那个,不调用构造方法,即构造方法的初始化代码根本不执行。
import java.io.Serializable;
public class Person implements Serializable {
private String name;
public Person(String name){
System.out.println(name+"诞生了");
this.name = name;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
}
Main.java
public class Main {
public static void main(String[] args) throws IOException,ClassNotFoundException {
String dataFile = "saved.data";
try(ObjectOutputStream output = new ObjectOutputStream(
new BufferedOutputStream(
new FileOutputStream(dataFile)))){
//依次写入int,String,Person对象
output.writeInt(999);
output.writeUTF("Hello world");
output.writeObject(new Person("小明"));
output.writeObject(new Person("小红"));
}
System.out.println("Read...");
try(ObjectInputStream input = new ObjectInputStream(
new BufferedInputStream(
new FileInputStream(dataFile)))){
//依次读取int,String,Person对象
System.out.println(input.readInt());
System.out.println(input.readUTF());
Person p1 = (Person) input.readObject();//构造方法不会执行
System.out.println(p1);
Person p2 = (Person) input.readObject();
System.out.println(p2);
}
}
}
为Person添加serialVersionUID,Main操作1次。
Person中serialVersionUID发生改变,只保留读取,再次执行Main,结果报错
Person.java
import java.io.Serializable;
public class Person implements Serializable {
public static final long serialVersionUID = 1234567890123456L;//Main执行1次后将UID修改为1234567890L
private String name;
public Person(String name){
System.out.println(name+"诞生了");
this.name = name;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
}
public class Main {
public static void main(String[] args) throws IOException,ClassNotFoundException {
String dataFile = "saved.data";
//修改UID后,注释写入代码块
try(ObjectOutputStream output = new ObjectOutputStream(
new BufferedOutputStream(
new FileOutputStream(dataFile)))){
//依次写入int,String,Person对象
output.writeInt(999);
output.writeUTF("Hello world");
output.writeObject(new Person("小明"));
output.writeObject(new Person("小红"));
}
System.out.println("Read...");
try(ObjectInputStream input = new ObjectInputStream(
new BufferedInputStream(
new FileInputStream(dataFile)))){
//依次读取int,String,Person对象
System.out.println(input.readInt());
System.out.println(input.readUTF());
Person p1 = (Person) input.readObject();//构造方法不会执行
System.out.println(p1);
Person p2 = (Person) input.readObject();
System.out.println(p2);
}
}
}
廖雪峰Java6 IO编程-2input和output-7序列化
标签:机制 main puts 类型 小明 zab try 使用 进制
原文地址:https://www.cnblogs.com/csj2018/p/10661999.html