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


Java ObjectOutputStream writeFields()用法及代碼示例


ObjectOutputStream類writeFields()方法

  • writeFields() 方法可在java.io包。
  • writeFields() 方法用於將緩衝字段寫入 ObjectOutputStream。
  • writeFields() 方法是一個非靜態方法,它隻能通過類對象訪問,如果我們嘗試使用類名訪問方法,那麽我們將得到一個錯誤。
  • writeFields() 方法可能會在寫入字段時拋出異常。
    • IOException:在寫入輸出流時出現任何輸入/輸出錯誤時,可能會拋出此異常。
    • 非活動異常: 當沒有調用 writeObject() 來寫入類對象的狀態時,可能會拋出此異常。

用法:

    public void writeFields();

參數:

  • 它不接受任何參數。

返回值:

該方法的返回類型是void,它什麽都不返回。

例:

// Java program to demonstrate the example 
// of void writeFields() method of ObjectOutputStream

import java.io.*;

public class WriteFieldsOfOOS {
 public static void main(String[] args) throws Exception {
  // Instantiates ObjectOutputStream , ObjectInputStream 
  // FileInputStream and FileOutputStream
  FileOutputStream file_out_stm = new FileOutputStream("D:\\includehelp.txt");
  ObjectOutputStream obj_out_stm = new ObjectOutputStream(file_out_stm);
  FileInputStream file_in_stm = new FileInputStream("D:\\includehelp.txt");

  ObjectInputStream obj_in_stm = new ObjectInputStream(file_in_stm);

  // By using writeInt() method is to write
  // integer to the obj_out_stm stream
  obj_out_stm.writeObject(new ReadFields());

  obj_out_stm.flush();

  // By using readObject() method is to read
  //  object and display fields
  ReadFields rf = (ReadFields) obj_in_stm.readObject();
  System.out.println("obj_in_stm.writeFields():" + rf.val);
 }

 static public class ReadFields implements Serializable {
  static int val = 12685;

  private static final ObjectStreamField[] serialPersistentFields = {
   new ObjectStreamField("val", Integer.TYPE)
  };

  private void readObject(ObjectInputStream oin)
  throws IOException, ClassNotFoundException {

   // Invokes readFields()
   ObjectInputStream.GetField fi = oin.readFields();

   // By using get() is to get var
   val = fi.get("val", 0);
  }

  private void writeObject(ObjectOutputStream oos) throws IOException {
   // By using putFields() method is to
   // write var into ObjectStreamField[]
   ObjectOutputStream.PutField fi = oos.putFields();
   fi.put("val", val);

   // Invokes writeFields()
   oos.writeFields();
  }
 }
}

輸出

obj_in_stm.writeFields():12685


相關用法


注:本文由純淨天空篩選整理自Preeti Jain大神的英文原創作品 Java ObjectOutputStream writeFields() Method with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。