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


Java ObjectInputStream readUnshared()用法及代碼示例


ObjectInputStream 類的 readUnshared() 方法從 ObjectInputStream 讀取 "unshared" 對象。此方法與 readObject 方法相同,不同之處在於它阻止對 readObject 和 readUnshared 的後續調用返回對通過此調用獲得的反序列化實例的其他引用。

用法

public Object readUnshared() throws IOException, ClassNotFoundException

參數

沒有傳遞參數。

返回

對反序列化對象的引用

拋出

類未找到異常

流損壞異常

對象流異常

可選數據異常

IOException

例子1

import java.io.*;
import static java.lang.System.out;
public class ObjectInputStreamreadUnsharedExample1 {
   public static void main(String[] args) {
      try {
      
         FileOutputStream outstream = new FileOutputStream("file1.txt");
         ObjectOutputStream objoutstream = new ObjectOutputStream(outstream);
         objoutstream.writeObject(new Task());
         objoutstream.flush();
         ObjectInputStream objinstream = new ObjectInputStream(new FileInputStream("file1.txt"));
          Task  obj = (Task) objinstream.readUnshared();
         System.out.println("" + obj.st);
      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }

   static class Task implements Serializable {
      String st = "Welcome to javaTpoint";
      private String readObject(ObjectInputStream in) 
         throws IOException, ClassNotFoundException {
         ObjectInputStream.GetField g = in.readFields();
         return (String) g.get("st", null);
      }
   }
}

輸出:

Welcome to javaTpoint

例子2

import java.io.*;
import java.io.ObjectInputStream;
public class ObjectInputStreamreadUnsharedExample2   {
   public static void main(String[] args) {
      try {
          FileOutputStream outstream = new FileOutputStream("file1.txt");
          ObjectOutputStream objoutstream = new ObjectOutputStream(outstream);
          FileInputStream instream = new FileInputStream("file2.txt");
          ObjectInputStream objinstream = new ObjectInputStream(instream);
          String str=objinstream.toString();
          objoutstream.writeObject(new task());
          objoutstream.writeObject(str);
          objoutstream.flush();
         ObjectInputStream objinputstram = new ObjectInputStream(new FileInputStream("file1.txt"));
         System.out.println("" + (String) objinstream.readObject());
         task obj1 = (task) objinputstram.readUnshared();
         System.out.println("string  in task class :" + obj1.str);
      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }
   static class task implements Serializable {
      String str = "javaTpoint";
      private void readObject(ObjectInputStream in)
         throws IOException, ClassNotFoundException {
         in.defaultReadObject();
      }
   }
}

輸出:

[email protected]
string that is in task class :javaTpoint




相關用法


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