1.对象序列化和反序列化
序列化是什么:将对象的状态存储到特定存储介质中的过程
支持可序列化(serializable):实现java.io.Serializable接口
对象序列化步骤:
创建一个对象输出流-ObjectOutputStream--->writeObject()方法输出序列化对象(oos.writeObject(stu)//stu为某类对象)
反序列化步骤:
创建一个对象输入流-ObjectInputStream--->readObject()方法读取序列化对象(ois.readObject(stu)//stu为某类对象)
例子:
//Book类需要实现Serializable接口,这样才能实例化
public class Book
implements Serializable
{
private int id;
private String name;
public Book(int id, String name) {
super();
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class BookManager {
/**
* 序列化
*/
public void serial(Book book) {
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream("D:/iodemo/serial/book.txt"));
// 实现序列化
oos.writeObject(book);
System.out.println("序列化成功");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (oos != null) {
oos.flush();
oos.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 反序列化
*
* @return
*/
public static Book unserial() {
ObjectInputStream ois = null;
Book book = null;
try {
ois = new ObjectInputStream(new FileInputStream("D:/iodemo/serial/book.txt"));
// 实现序列化
book = (Book) ois.readObject();
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 {
if (ois != null) {
ois.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return book;
}
public static void main(String[] args) {
BookManager bm = new BookManager();
Book book = new Book(1, "哈利波特");
bm.serial(book);
Book book2 = unserial();
System.out.println("编号:" + book2.getId() + " 书名:" + book2.getName());
}
}