序列化是用来处理对象流的机制,对象流即将对象的内容进行流化,对流化后的对象进行读写操作、网路传输,序列化是为了解决对象流读写操作时可能引发的问题(如果不进行序列化可能会存在数据乱序的问题)。
java实现序列化需要实现Serializable接口,该接口是一个标准性接口,表示该类对象可以进行序列化
序列化除了能够实现对象的持久化之外,还能够用于对象的深度克隆
public class Person implements Serializable {
private String name;
private int 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;} public Person(String name, int age) {this.name = name;this.age = age;}
//对象克隆
public Person myClone(){
Person person=null;
try {
ByteArrayOutputStream bos=new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(this);
ObjectInputStream ois=new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
person=(Person)ois.readObject();
bos.close();
oos.close();
ois.close();
return person;
}catch (Exception e){
}
return person;
}
}public class Test {
public static void main(String[] arges){ try {
File file = new File("c:/person.txt");
if (!file.exists()) {
file.createNewFile();
}
Person person=new Person("张三",10);
//序列化 ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));//创建对象输出字节流
oos.writeObject(person);
oos.close();
//反序列化 ObjectInputStream ois=new ObjectInputStream(new FileInputStream(file));//创建对象输入字节流
Person per=(Person) ois.readObject();
System.out.print(per.getName()+" "+per.getAge());
ois.close();
}catch (Exception e){
}}
}