Clase Java.io.ObjectOutputStream en Java | conjunto 2

Clase Java.io.ObjectOutputStream en Java | Serie 1

Más métodos:

  • void write(byte[] buf) : Escribe una array de bytes. Este método se bloqueará hasta que el byte se escriba realmente.
    Syntax :public void write(byte[] buf)
               throws IOException
    Parameters:
    buf - the data to be written
    Throws:
    IOException 
    
  • void write(byte[] buf, int off, int len) : Escribe una subarray de bytes.
    Syntax :public void write(byte[] buf,
             int off,
             int len)
               throws IOException
    Parameters:
    buf - the data to be written
    off - the start offset in the data
    len - the number of bytes that are written
    Throws:
    IOException
  • void write(int val) : Escribe un byte. Este método se bloqueará hasta que el byte se escriba realmente.
    Syntax :public void write(int val)
               throws IOException
    Parameters:
    val - the byte to be written to the stream
    Throws:
    IOException 
  • void writeBoolean(boolean val) : Escribe un valor booleano.
    Syntax :public void writeBoolean(boolean val)
                      throws IOException
    Parameters:
    val - the boolean to be written
    Throws:
    IOException 
  • void writeByte(int val) : Escribe un byte de 8 bits.
    Syntax :public void writeByte(int val)
                   throws IOException
    Parameters:
    val - the byte value to be written
    Throws:
    IOException
  • void writeBytes(String str) : Escribe una string como una secuencia de bytes.
    Syntax :public void writeBytes(String str)
                    throws IOException
    Parameters:
    str - the String of writeBytes to be written
    Throws:
    IOException
  • void writeChar(int val) : Escribe un carácter de 16 bits.
    Syntax :public void writeChar(int val)
                   throws IOException
    Parameters:
    val - the char value to be written
    Throws:
    IOException
  • void writeChars(String str) : Escribe una string como una secuencia de caracteres.
    Syntax :public void writeChars(String str)
                    throws IOException
    Parameters:
    str - the String of chars to be written
    Throws:
    IOException
  • protected void writeClassDescriptor(ObjectStreamClass desc) : escribe el descriptor de clase especificado en ObjectOutputStream. Los descriptores de clase se utilizan para identificar las clases de objetos escritos en la secuencia. Las subclases de ObjectOutputStream pueden anular este método para personalizar la forma en que se escriben los descriptores de clase en el flujo de serialización. El método correspondiente en ObjectInputStream, readClassDescriptor, debe anularse para reconstituir el descriptor de clase a partir de su representación de secuencia personalizada. De forma predeterminada, este método escribe descriptores de clase según el formato definido en la especificación de serialización de objetos.
    Syntax :protected void writeClassDescriptor(ObjectStreamClass desc)
                                 throws IOException
    Parameters:
    desc - class descriptor to write to the stream
    Throws:
    IOException
  • void writeDouble(double val) : Escribe un doble de 64 bits.
    Syntax :public void writeDouble(double val)
                     throws IOException
    Parameters:
    val - the double value to be written
    Throws:
    IOException
  • void writeFields() : escribe los campos almacenados en el búfer en la secuencia.
    Syntax :public void writeFields()
                     throws IOException
    Throws:
    IOException
    NotActiveException
  • void writeFloat(float val) : Escribe un flotante de 32 bits.
    Syntax :public void writeFloat(float val)
                    throws IOException
    Parameters:
    val - the float value to be written
    Throws:
    IOException 
  • void writeInt(int val) : Escribe un int de 32 bits.
    Syntax :public void writeInt(int val)
                  throws IOException
    Parameters:
    val - the integer value to be written
    Throws:
    IOException
    
  • void writeLong(long val) : Escribe una longitud de 64 bits.
    Syntax :public void writeLong(long val)
                   throws IOException
    Parameters:
    val - the long value to be written
    Throws:
    IOException 
  • void writeObject(Object obj) : escribe el objeto especificado en ObjectOutputStream. Se escriben la clase del objeto, la firma de la clase y los valores de los campos no transitorios y no estáticos de la clase y todos sus supertipos. . La serialización predeterminada para una clase se puede anular utilizando los métodos writeObject y readObject. Los objetos a los que hace referencia este objeto se escriben de forma transitiva para que un ObjectInputStream pueda reconstruir un gráfico equivalente completo de objetos.
    Syntax :public final void writeObject(Object obj)
                           throws IOException
    Parameters:
    obj - the object to be written
    Throws:
    InvalidClassException 
    NotSerializableException 
    IOException
  • protected void writeObjectOverride(Object obj) : método utilizado por las subclases para anular el método predeterminado writeObject. Este método es llamado por subclases de confianza de ObjectInputStream que construyeron ObjectInputStream utilizando el constructor protegido sin argumentos. Se espera que la subclase proporcione un método de anulación con el modificador «final».
    Syntax :protected void writeObjectOverride(Object obj)
                                throws IOException
    Parameters:
    obj - object to be written to the underlying stream
    Throws:
    IOException 
  • void writeShort(int val) : Escribe un corto de 16 bits.
    Syntax :public void writeShort(int val)
                    throws IOException
    Parameters:
    val - the short value to be written
    Throws:
    IOException
  • protected void writeStreamHeader() : El método writeStreamHeader se proporciona para que las subclases puedan agregar o anteponer su propio encabezado a la secuencia. Escribe el número mágico y la versión de la secuencia.
    Syntax :protected void writeStreamHeader()
                              throws IOException
    Throws:
    IOException
  • void writeUnshared(Object obj) : Escribe un objeto «no compartido» en ObjectOutputStream. Este método es idéntico a writeObject, excepto que siempre escribe el objeto dado como un objeto nuevo y único en la secuencia (a diferencia de una referencia inversa que apunta a una instancia previamente serializada). Específicamente:
    • Un objeto escrito a través de writeUnshared siempre se serializa de la misma manera que un objeto que aparece recientemente (un objeto que aún no se ha escrito en la secuencia), independientemente de si el objeto se ha escrito previamente o no.
    • Si se usa writeObject para escribir un objeto que se ha escrito previamente con writeUnshared, la operación writeUnshared anterior se trata como si fuera una escritura de un objeto separado. En otras palabras, ObjectOutputStream nunca generará referencias inversas a datos de objetos escritos por llamadas a writeUnshared.

    Si bien escribir un objeto a través de writeUnshared no garantiza en sí mismo una referencia única al objeto cuando se deserializa, permite que un solo objeto se defina varias veces en una secuencia, de modo que varias llamadas a readUnshared por parte del receptor no entren en conflicto. Tenga en cuenta que las reglas descritas anteriormente solo se aplican al objeto de nivel base escrito con writeUnshared, y no a ningún subobjeto referenciado transitivamente en el gráfico de objeto que se va a serializar.
    Las subclases de ObjectOutputStream que anulan este método solo se pueden construir en contextos de seguridad que posean el Permiso Serializable «enableSubclassImplementation»; cualquier intento de instanciar una subclase de este tipo sin este permiso provocará que se lance una SecurityException.

    Syntax :public void writeUnshared(Object obj)
                       throws IOException
    Parameters:
    obj - object to write to stream
    Throws:
    NotSerializableException
    InvalidClassException
    IOException 
  • void writeUTF(String str): escritura de datos primitivos de esta string en formato UTF-8 modificado. Tenga en cuenta que existe una diferencia significativa entre escribir una string en la transmisión como datos primitivos o como un objeto. Una instancia de String escrita por writeObject se escribe en la secuencia inicialmente como String. Las futuras llamadas a writeObject() escriben referencias a la string en la transmisión.
    Syntax :public void writeUTF(String str)
                  throws IOException
    Parameters:
    str - the String to be written
    Throws:
    IOException
  • void flush() : Vacía la corriente. Esto escribirá los bytes de salida almacenados en el búfer y los vaciará a la secuencia subyacente.
    Syntax :public void flush()
               throws IOException
    Throws:
    IOException

Programa :

//Java program demonstrating ObjectOutputStream
//write methods
import java.io.*;
class ObjectOutputStreamDemo
{
    public static void main(String[] args) throws IOException, ClassNotFoundException 
    {
        FileOutputStream fout = new FileOutputStream("file.txt");
        ObjectOutputStream oot = new ObjectOutputStream(fout);
          
        String a = "GeeksforGeeks";
        String b = "Geek";
        byte[] be = {'A','B','C'};
  
        //illustrating write()
        oot.write(1);
  
        //illustrating writeInt(int i)
        oot.writeInt(1);
  
        //illustrating writeBoolean(boolean a)
        oot.writeBoolean(true);
  
        //illustrating writeObject(Object x)
        oot.writeObject(a);
  
        //illustrating writeByte(byte a)
        oot.writeByte(65);
  
        //illustrating writeBytes(String b)
        oot.writeBytes(b);
  
        //illustrating writeDouble(double d)
        oot.writeDouble(2.3);
  
        //illustrating writeUTF(String str)
        oot.writeUTF(a);
  
        //illustrating writeFloat(float x)
        oot.writeFloat(2.42f);
  
        //illustrating writeLone(long x)
        oot.writeLong(234342347908l);
  
        //illustrating writeChars(String a)
        oot.writeChars(a);
  
        //illustrating writeShort(int val)
        oot.writeShort(2);
  
        //illustrating write(byte[] buff)
        oot.write(be);
          
        //flushing the stream
        oot.flush();
          
        oot.close();
          
        byte c[]=new byte[4];
        char c1[]=new char[13];
          
        FileInputStream fin = new FileInputStream("file.txt");
        ObjectInputStream oit = new ObjectInputStream(fin);
          
        System.out.println(oit.read());
        System.out.println(oit.readInt());
        System.out.println(oit.readBoolean());
        System.out.println(oit.readObject());
        System.out.println(oit.readByte());
        oit.read(c);
          
        for (int i = 0; i  < 4 ; i++) 
        {
            System.out.print((char)c[i]);
        }
          
        System.out.println();
        System.out.println(oit.readDouble());
        System.out.println(oit.readUTF());
        System.out.println(oit.readFloat());
        System.out.println(oit.readLong());
          
        for (int i = 0; i < 13 ; i++)
        {
            System.out.print(oit.readChar());
        }
          
        System.out.println();
        System.out.println(oit.readShort());
        oit.readFully(be);
          
        for (int i = 0; i < 3 ; i++) 
        {
            System.out.print((char)be[i]);
        }
        oit.close();
    }
}

Producción :

1
1
true
GeeksforGeeks
65
Geek
2.3
GeeksforGeeks
2.42
234342347908
GeeksforGeeks
2
ABC

Programa 2:

//Java program illustrating ObjectOutputStream
//write methods
import java.io.*;
class ObjectOutputStreamDemo
{
    public static void main(String[] args) throws IOException,
            ClassNotFoundException
    {
            FileOutputStream out = new FileOutputStream("file.txt");
            ObjectOutputStream oout = new ObjectOutputStream(out);
            oout.writeObject(new demo());
              
            //illustrating writeUnshared()
            //Writes an "unshared" object to the ObjectOutputStream.
            oout.writeUnshared(14);
              
            //flush the stream
            oout.flush();
              
            oout.close();
  
            FileInputStream fin=new FileInputStream("file.txt");
            ObjectInputStream ois=new ObjectInputStream(fin);
  
            // read an object from the stream and cast it to demo
            demo obj = (demo)ois.readObject();
              
            System.out.println( obj.var);
            System.out.println(ois.readUnshared());
    }
}
class demo implements Serializable
{
    static int var = 25;
          
    // assign a new serialPersistentFields
    private static final ObjectStreamField[] serialPersistentFields = 
    {
        new ObjectStreamField("var", Integer.TYPE)
    };
  
    private void readObject(ObjectInputStream in)
    throws IOException, ClassNotFoundException
    {
        // makes them available by name.
        ObjectInputStream.GetField fields = in.readFields();
              
        //Get the value of the named int field from the persistent field.
        var = fields.get("var", 0);
    }
  
    private void writeObject(ObjectOutputStream out)
                throws IOException
    {
        // write into the ObjectStreamField array the variable string
        ObjectOutputStream.PutField fields = out.putFields();
        fields.put("var", var);
              
        //Write the buffered fields to the stream
        out.writeFields();
  
    }
}

Producción :

25
14

Este artículo es una contribución de Nishant Sharma . Si le gusta GeeksforGeeks y le gustaría contribuir, también puede escribir un artículo usando contribuya.geeksforgeeks.org o envíe su artículo por correo a contribuya@geeksforgeeks.org. Vea su artículo que aparece en la página principal de GeeksforGeeks y ayude a otros Geeks.

Escriba comentarios si encuentra algo incorrecto o si desea compartir más información sobre el tema tratado anteriormente.

Publicación traducida automáticamente

Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *