ObjectInputStream与ObjectOutputStream类实现对象的存取

9/6/2015来源:Java教程人气:2021

ObjectInputStream与ObjectOutputStream类实现对象的存取

1.

ObjectInputStream与ObjectOutputStream类所读写的对象必须实现Serializable接口,对象中的transient和static类型成员变量不会被读取和写入

2.

Serializable是个对象序列化接口,只有序列化才能实现对象存取

3.读写方法(存取BOOK类)

 1 public class Util { 2     public String path = "c:/book.db"; 3  4     public  ArrayList<Book> readBook() { 5         ArrayList<Book> s = new ArrayList<Book>(); 6         try { 7             FileInputStream fis = new FileInputStream(path); 8             ObjectInputStream ois = new ObjectInputStream(fis); 9             s = (ArrayList<Book>)ois.readObject();10             fis.close();11             ois.close();12         } catch (Exception e) {13         }14         return s;15 16     }17 18     public void writeBook(Book book) {19         ArrayList<Book> books = readBook();20         books.add(book);21         try {22             FileOutputStream fos = new FileOutputStream(path);23             ObjectOutputStream oos = new ObjectOutputStream(fos);24             oos.writeObject(books);25             fos.close();26             oos.close();27         } catch (Exception e) {28         }29 30     }31 }

----------------------------------------------------------------------------------------------------------------------------------------------------------