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.yiibai; 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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM