當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Java Java.io.ObjectOutputStream.writeObject()用法及代碼示例


描述

這個java.io.ObjectOutputStream.writeObject(Object obj)方法將指定的對象寫入 ObjectOutputStream。對象的類、類的簽名以及類及其所有超類型的非瞬態和非靜態字段的值都被寫入。可以使用 writeObject 和 readObject 方法覆蓋類的默認序列化。此對象引用的對象是傳遞性寫入的,以便可以通過 ObjectInputStream 重建完整的等效對象圖。

聲明

以下是聲明java.io.ObjectOutputStream.writeObject()方法。

public final void writeObject(Object obj)

參數

obj− 要寫入的對象。

返回值

此方法不返回值。

異常

  • InvalidClassException- 序列化使用的類有問題。

  • NotSerializableException− 某些要序列化的對象沒有實現 java.io.Serializable 接口。

  • IOException− 底層 OutputStream 拋出的任何異常。

示例

下麵的例子展示了使用java.io.ObjectOutputStream.writeObject()方法。

package com.tutorialspoint;

import java.io.*;

public class ObjectOutputStreamDemo {
   public static void main(String[] args) {
      String s = "Hello world!";
      int i = 897648764;
      
      try {
         // create a new file with an ObjectOutputStream
         FileOutputStream out = new FileOutputStream("test.txt");
         ObjectOutputStream oout = new ObjectOutputStream(out);

         // write something in the file
         oout.writeObject(s);
         oout.writeObject(i);

         // close the stream
         oout.close();

         // create an ObjectInputStream for the file we created before
         ObjectInputStream ois = new ObjectInputStream(new FileInputStream("test.txt"));

         // read and print what we wrote before
         System.out.println("" + (String) ois.readObject());
         System.out.println("" + ois.readObject());
      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }
}

讓我們編譯並運行上麵的程序,這將產生以下結果 -

Hello world!
897648764

相關用法


注:本文由純淨天空篩選整理自 Java.io.ObjectOutputStream.writeObject() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。