對象的序列化與反序列化Demo

這是個簡單的Demo……
/**
 * 對象的序列化與反序列化
 * ps:
 * 1. 要序列化的對象必須實現Serialzalbe接口(……我竟然忘了)
 * 2. 反序列化的is.readObject()方法讀到文件末尾時,竟然拋出EOFException而非返回特殊值(-1,null之類),JDKAPI也表示這很坑爹。
 * @author garview
 *
 * @Date  2013-11-4上午11:36:28
 */
public class SerializeDemo {
 public static void main(String[] args) {
  try {
   File file = new File("c:/test.java");
   ser(file, intiData());
   reverseSer(file);
  } catch (FileNotFoundException e) {
   e.printStackTrace();
   System.out.println("未找到文件");
  } catch (IOException e) {
   e.printStackTrace();
   System.out.println("寫入對象失敗");
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  }
 } java

 // 1.序列化對象(初始化對象、搭建傳輸管道,寫對象,關閉管道資源)
 public static void ser(File file, ArrayList<Book> books)
   throws FileNotFoundException, IOException { .net

  // 搭建傳輸管道
  if (!file.exists()) {
   file.createNewFile();
  }
  FileOutputStream fos = new FileOutputStream(file);
  ObjectOutputStream os = new ObjectOutputStream(fos);
  // 寫對象
  for (Book temp : books) {
   os.writeObject(temp);
  } 對象

  // 寫入null,方便反序列化時判斷結束
  os.writeObject(null); 接口

  os.close();
 } three

 // 1.反序列化對象(初始化對象、搭建傳輸管道,寫對象,關閉管道資源)
 public static void reverseSer(File src) throws FileNotFoundException,
   IOException, ClassNotFoundException {
  FileInputStream fis = new FileInputStream(src);
  ObjectInputStream is = new ObjectInputStream(fis); 資源

  ArrayList<Book> books = new ArrayList<Book>(); get

  Object temp = null;
  while (true) {
   //注意讀到文件末尾會拋出EOFException
   temp = is.readObject();
   if (temp == null) {
    break;
   }
   books.add((Book) temp);
  } it

  for (Book temp2 : books) {
   System.out.println(temp2.toString());
  }
  is.close();
 } io

 public static ArrayList<Book> intiData() {
  // 初始化對象
  Book one = new Book("西遊釋厄傳", 90, 55.0);
  Book two = new Book("西遊釋厄傳2", 90, 55.0);
  Book three = new Book("西遊釋厄傳3", 90, 55.0); class

  ArrayList<Book> books = new ArrayList<Book>();   books.add(one);   books.add(two);   books.add(three);   return books;  }

相關文章
相關標籤/搜索