logo

Classe Java.io.ObjectOutputStream in Java | Insieme 1

Un ObjectOutputStream scrive tipi di dati primitivi e grafici di oggetti Java su un OutputStream. Gli oggetti possono essere letti (ricostituiti) utilizzando un ObjectInputStream. L'archiviazione persistente degli oggetti può essere ottenuta utilizzando un file per il flusso. 

  • Solo gli oggetti che supportano l'interfaccia java.io.Serializable possono essere scritti nei flussi. La classe di ogni oggetto serializzabile è codificata includendo il nome della classe e la firma della classe, i valori dei campi e degli array dell'oggetto e la chiusura di qualsiasi altro oggetto a cui si fa riferimento dagli oggetti iniziali.
  • Java ObjectOutputStream viene spesso utilizzato insieme a Java ObjectInputStream. ObjectOutputStream viene utilizzato per scrivere gli oggetti Java e ObjectInputStream viene utilizzato per leggere nuovamente gli oggetti. 

Costruttori:   

    protetto ObjectOutputStream() :Fornire un modo per le sottoclassi che stanno reimplementando completamente ObjectOutputStream di non dover allocare i dati privati ​​appena utilizzati da questa implementazione di ObjectOutputStream.OggettoOutputStream(OutputStream fuori):Crea un ObjectOutputStream che scrive nell'OutputStream specificato. 

Metodi:   



tostring in Java
    protetto void annotateClass(Class cl) :Le sottoclassi possono implementare questo metodo per consentire la memorizzazione dei dati della classe nel flusso. Per impostazione predefinita questo metodo non fa nulla. Il metodo corrispondente in ObjectInputStream è risolvereClass. Questo metodo viene chiamato esattamente una volta per ogni classe univoca nel flusso. Il nome della classe e la firma saranno già stati scritti nello stream. Questo metodo può utilizzare liberamente l'ObjectOutputStream per salvare qualunque rappresentazione della classe ritenga opportuna (ad esempio i byte del file di classe). Il metodo risolvereClass nella sottoclasse corrispondente di ObjectInputStream deve leggere e utilizzare tutti i dati o oggetti scritti da annotateClass. 
  Syntax :  protected void annotateClass(Class cl) throws IOException   Parameters:   cl - the class to annotate custom data for   Throws:   IOException 
Java
//Java program demonstrating ObjectOutputStream methods //illustrating annotateClass(Class cl) method import java.io.*; class ObjectOutputStreamDemo extends ObjectOutputStream {  public ObjectOutputStreamDemo(OutputStream out) throws IOException  {  super(out);  }    public static void main(String[] args) throws IOException  ClassNotFoundException   {  FileOutputStream fout = new FileOutputStream('file.txt');  ObjectOutputStreamDemo oot = new ObjectOutputStreamDemo(fout);  Character c = 'A';    //illustrating annotateClass(Class cl) method  oot.annotateClass(Character.class);    //Write the specified object to the ObjectOutputStream  oot.writeObject(c);    //flushing the stream  oot.flush();    //closing the stream  oot.close();    FileInputStream fin = new FileInputStream('file.txt');  ObjectInputStream oit = new ObjectInputStream(fin);  System.out.print(oit.readObject());  oit.close();  } } 

Produzione :  

A
    protetto void annotateProxyClass(Class cl) :Le sottoclassi possono implementare questo metodo per archiviare dati personalizzati nel flusso insieme ai descrittori per le classi proxy dinamiche. Questo metodo viene chiamato esattamente una volta per ogni descrittore di classe proxy univoco nel flusso. L'implementazione predefinita di questo metodo in ObjectOutputStream non fa nulla.
    Il metodo corrispondente in ObjectInputStream è risolvereProxyClass. Per una determinata sottoclasse di ObjectOutputStream che sovrascrive questo metodo, il metodo risolvereProxyClass nella corrispondente sottoclasse di ObjectInputStream deve leggere tutti i dati o gli oggetti scritti da annotateProxyClass. 
  Syntax :  protected void annotateProxyClass(Class cl) throws IOException   Parameters:   cl - the proxy class to annotate custom data for   Throws:   IOException
Java
//Java program demonstrating ObjectOutputStream  //illustrating annotateProxyClass(Class cl) method import java.io.*; class ObjectOutputStreamDemo extends ObjectOutputStream {  public ObjectOutputStreamDemo(OutputStream out) throws IOException  {  super(out);  }    public static void main(String[] args) throws IOException   ClassNotFoundException  {  FileOutputStream fout = new FileOutputStream('file.txt');  ObjectOutputStreamDemo oot = new ObjectOutputStreamDemo(fout);    Character c = 'A';    //illustrating annotateProxyClass(Class cl) method  oot.annotateProxyClass(Character.class);    //Write the specified object to the ObjectOutputStream  oot.writeObject(c);    //flushing  oot.flush();    //closing the stream  oot.close();    FileInputStream fin = new FileInputStream('file.txt');  ObjectInputStream oit = new ObjectInputStream(fin);  System.out.print(oit.readObject());  oit.close();  } } 

Produzione :  

A
    vuoto vicino() :Chiude il flusso. Questo metodo deve essere chiamato per rilasciare eventuali risorse associate al flusso. 
  Syntax :  public void close() throws IOException   Throws:   IOException
Java
//Java program demonstrating ObjectOutputStream  //illustrating close() method import java.io.*; class ObjectOutputStreamDemo {  public static void main(String[] args) throws IOException  {  FileOutputStream fout = new FileOutputStream('file.txt');  ObjectOutputStream oot = new ObjectOutputStream(fout);  oot.write(3);    //illustrating close()  oot.close();    FileInputStream fin = new FileInputStream('file.txt');  ObjectInputStream oit = new ObjectInputStream(fin);  System.out.println(oit.read());  oit.close();  } } 
    Produzione : 
3
    void defaultWriteObject() :Scrivi i campi non statici e non transitori della classe corrente in questo flusso. Questo può essere chiamato solo dal metodo writeObject della classe da serializzare. Lancerà NotActiveException se viene chiamato diversamente. 
  Syntax :  public void defaultWriteObject() throws IOException   Throws:   IOException 
Java
//Java program demonstrating ObjectOutputStream //illustrating defaultWriteObject() method import java.io.*; class ObjectOutputStreamDemo {  public static void main(String[] arg) throws IOException  ClassNotFoundException  {  Character a = 'A';  FileOutputStream fout = new FileOutputStream('file.txt');  ObjectOutputStream oot = new ObjectOutputStream(fout);  oot.writeChar(a);  oot.flush();    // close the stream  oot.close();    FileInputStream fin = new FileInputStream('file.txt');  ObjectInputStream oit = new ObjectInputStream(fin);    // reading the character  System.out.println(oit.readChar());  } }  class demo implements Serializable   {  String s = 'GeeksfoGeeks';  private void writeObject(ObjectOutputStream out)  throws IOException ClassNotFoundException  {  //demonstrating defaultWriteObject()  out.defaultWriteObject();  }  }  } 

Produzione :  

A
    drenaggio del vuoto protetto() :Scarica tutti i dati memorizzati nel buffer in ObjectOutputStream. Simile a flush ma non propaga il flush al flusso sottostante. 
  Syntax :  protected void drain() throws IOException   Throws:   IOException
Java
//Java program demonstrating ObjectOutputStream methods //illustrating drain() method import java.io.*; class ObjectOutputStreamDemo extends ObjectOutputStream {  public ObjectOutputStreamDemo(OutputStream out) throws IOException  {  super(out);  }  public static void main(String[] arg) throws IOException  ClassNotFoundException  {  FileOutputStream fout = new FileOutputStream('file.txt');  ObjectOutputStream oot = new ObjectOutputStream(fout);  ObjectOutputStreamDemo obj = new ObjectOutputStreamDemo(oot);    //illustrating drain()  obj.drain();    //closing the underlying stream  oot.close();  fout.close();  } } 
    abilitazione booleana protettaReplaceObject(abilitazione booleana):Abilita il flusso a sostituire gli oggetti nel flusso. Quando abilitato, il metodo replaceObject viene chiamato per ogni oggetto serializzato. 
    Se abilita è vero ed è installato un gestore della sicurezza, questo metodo chiama prima il metodo checkPermission del gestore della sicurezza con un'autorizzazione SerializablePermission('enableSubstitution') per garantire che sia possibile abilitare il flusso per sostituire gli oggetti nel flusso. 
  Syntax :  protected boolean enableReplaceObject(boolean enable) throws SecurityException   Parameters:   enable - boolean parameter to enable replacement of objects   Returns:   the previous setting before this method was invoked   Throws:   SecurityException
Java
//Java program demonstrating ObjectOutputStream //illustrating enableReplaceObject method import java.io.*; class ObjectOutputStreamDemo extends ObjectOutputStream  {  public ObjectOutputStreamDemo(OutputStream out) throws IOException  {  super(out);  }  public static void main(String[] args) throws IOException   ClassNotFoundException  {  FileOutputStream fout = new FileOutputStream('file.txt');  ObjectOutputStreamDemo oot = new ObjectOutputStreamDemo(fout);  Character c = 'A';    //illustrating enableReplaceObject method  System.out.println(oot.enableReplaceObject(true));    //Write the specified object to the ObjectOutputStream  oot.writeObject(c);    //flushing  oot.flush();    //closing the stream  oot.close();    FileInputStream fin = new FileInputStream('file.txt');  ObjectInputStream oit = new ObjectInputStream(fin);  System.out.print(oit.readObject());  oit.close();  } } 

Produzione :  

false A
    ObjectOutputStream.PutField putFields():Recupera l'oggetto utilizzato per bufferizzare i campi persistenti da scrivere nel flusso. I campi verranno scritti nel flusso quando viene chiamato il metodo writeFields. 
  Syntax :  public ObjectOutputStream.PutField putFields() throws IOException   Returns:   an instance of the class Putfield that holds the serializable fields   Throws:   IOException
Java
//Java program demonstrating ObjectOutputStream //illustrating PutField method import java.io.*; class ObjectOutputStreamDemo {  public static void main(String[] arg) throws IOException  ClassNotFoundException  {  Character a ='A';  FileOutputStream fout = new FileOutputStream('file.txt');  ObjectOutputStream oot = new ObjectOutputStream(fout);  oot.writeChar(a);  oot.flush();    // close the stream  oot.close();    FileInputStream fin = new FileInputStream('file.txt');  ObjectInputStream oit = new ObjectInputStream(fin);    // reading the character  System.out.println(oit.readChar());  } } class demo implements Serializable {  private void writeObject(ObjectOutputStream out)  throws IOException ClassNotFoundException  {  // Retrieve the object used to buffer  // persistent fields to be written to the stream  ObjectOutputStream.PutField fields = out.putFields();  } } 

Produzione :  

aggiungi la stringa java
A
    Oggetto protetto replaceObject(Oggetto oggetto):Questo metodo consentirà alle sottoclassi attendibili di ObjectOutputStream di sostituire un oggetto con un altro durante la serializzazione. La sostituzione degli oggetti è disabilitata finché non viene chiamato EnableReplaceObject. Il metodo EnableReplaceObject verifica che il flusso che richiede la sostituzione possa essere considerato attendibile. La prima occorrenza di ciascun oggetto scritto nel flusso di serializzazione viene passata a replaceObject. I successivi riferimenti all'oggetto vengono sostituiti dall'oggetto restituito dalla chiamata originale a replaceObject. Per garantire che lo stato privato degli oggetti non venga esposto involontariamente, solo i flussi attendibili possono utilizzare replaceObject. 
    Questo metodo viene chiamato solo una volta quando ciascun oggetto viene incontrato per la prima volta. Tutti i successivi riferimenti all'oggetto verranno reindirizzati al nuovo oggetto. Questo metodo dovrebbe restituire l'oggetto da sostituire o l'oggetto originale.
    Null può essere restituito come oggetto da sostituire ma può causare NullReferenceException nelle classi che contengono riferimenti all'oggetto originale poiché potrebbero aspettarsi un oggetto invece di null. 
  Syntax :  protected Object replaceObject(Object obj) throws IOException   Parameters:   obj - the object to be replaced   Returns:   the alternate object that replaced the specified one   Throws:   IOException
Java
//Java program demonstrating ObjectOutputStream //illustrating replaceObject method import java.io.*; class ObjectOutputStreamDemo extends ObjectOutputStream {  public ObjectOutputStreamDemo(OutputStream out) throws IOException  {  super(out);  }  public static void main(String[] args) throws IOException   ClassNotFoundException   {  FileOutputStream fout = new FileOutputStream('file.txt');  ObjectOutputStreamDemo oot = new ObjectOutputStreamDemo(fout);  String a = 'forGeeks';  String b = 'Geeks';  //Write the specified object to the ObjectOutputStream  oot.writeObject(a);    //flushing the stream  oot.flush();  oot.enableReplaceObject(true);    //illustrating replaceObject  System.out.print(oot.replaceObject(b));    //closing the stream  oot.close();    FileInputStream fin = new FileInputStream('file.txt');  ObjectInputStream oit = new ObjectInputStream(fin);  System.out.print(oit.readObject());  oit.close();  } } 

Produzione :  

GeeksforGeeks
    void useProtocolVersion(int versione) :Specifica la versione del protocollo del flusso da utilizzare durante la scrittura del flusso. Questa routine fornisce un hook per consentire alla versione corrente di Serializzazione di scrivere in un formato compatibile con una versione precedente del formato del flusso.
    Verrà fatto ogni sforzo per evitare di introdurre ulteriori incompatibilità con le versioni precedenti; tuttavia a volte non esiste altra alternativa. 
  Syntax :  public void useProtocolVersion(int version) throws IOException   Parameters:   version - use ProtocolVersion from java.io.ObjectStreamConstants.   Throws:   IllegalStateException IllegalArgumentException IOException 
Java
 //Java program demonstrating ObjectOutputStream  //illustrating useProtocolVersion() method import java.io.*; class ObjectOutputStreamDemo extends ObjectOutputStream {  public ObjectOutputStreamDemo(OutputStream out) throws IOException  {  super(out);  }  public static void main(String[] args) throws IOException   ClassNotFoundException   {  FileOutputStream fout = new FileOutputStream('file.txt');  ObjectOutputStreamDemo oot = new ObjectOutputStreamDemo(fout);  String a = 'forGeeks';  String b = 'Geeks';  //illustrating useProtocolVersion()  oot.useProtocolVersion(ObjectStreamConstants.PROTOCOL_VERSION_2);  //Write the specified object to the ObjectOutputStream  oot.writeObject(b);  oot.writeObject(a);  //flushing the stream  oot.flush();  oot.close();  FileInputStream fin = new FileInputStream('file.txt');  ObjectInputStream oit = new ObjectInputStream(fin);  System.out.print(oit.readObject());  System.out.print(oit.readObject());  oit.close();  } } 

Produzione :  

GeeksforGeeks

Articolo successivo: Classe Java.io.ObjectOutputStream in Java | Insieme 2

tipo in Java


 

Crea quiz