序列化和反序列化
序列化:
序列化要实现Serializable这个空接口,要生成uid
序列化:
private static final long serialVersionUID = 1L; public Book(){ } public Book(String bookName, String autotName, double price) { this.bookName = bookName; this.autotName = autotName; this.price = price; } private String bookName; private String autotName; //transient 不需要序列化的对象 private double price; public String getBookName() { return bookName; } public void setBookName(String bookName) { this.bookName = bookName; } public String getAutotName() { return autotName; } public void setAutotName(String autotName) { this.autotName = autotName; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } @Override public String toString() { return "Book [bookName=" + bookName + ", autotName=" + autotName + ", price=" + price + "]"; }
FileOutputStream fos = null; ObjectOutputStream oos = null; File file = new File("book.txt"); try { fos = new FileOutputStream(file); oos = new ObjectOutputStream(fos); Book book = new Book("听雪楼", "沧月", 30); oos.writeObject(book); oos.flush(); fos.close(); oos.close(); } catch (IOException e) { e.printStackTrace(); }
反序列化:
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("book.txt"))); Object book = ois.readObject(); System.out.println(book); //反序列化会报一个空的错 //这里抛出了没有处理
集合序列化:
List<Book> list = new ArrayList<Book>(); list.add(new Book("听雪楼1", "沧月1", 20)); list.add(new Book("听雪楼2", "沧月2", 20)); list.add(new Book("听雪楼3", "沧月3", 20)); list.add(new Book("听雪楼4", "沧月4", 20)); list.add(new Book("听雪楼5", "沧月5", 20)); File file = new File("array.txt"); ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file)); oos.writeObject(list); oos.flush(); oos.close(); ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file)); List<Book> books = (List<Book>) ois.readObject(); ois.close(); for (Book book : books) { System.out.println(book); }