Класс Java.io.ObjectOutputStream в Java | Комплект 1
ObjectOutputStream записывает примитивные типы данных и графики объектов Java в OutputStream. Объекты могут быть прочитаны (воссозданы) с помощью ObjectInputStream. Постоянное хранение объектов может быть выполнено с помощью файла для потока.
- В потоки могут быть записаны только объекты, поддерживающие интерфейс java.io.Serializable. Класс каждого сериализуемого объекта кодируется, включая имя класса и сигнатуру класса, значения полей и массивов объекта, а также закрытие любых других объектов, на которые ссылаются исходные объекты.
- Java ObjectOutputStream часто используется вместе с Java ObjectInputStream. ObjectOutputStream используется для записи объектов Java, а ObjectInputStream используется для повторного чтения объектов.
Конструкторы:
- protected ObjectOutputStream (): предоставить подклассам, которые полностью реализуют ObjectOutputStream, возможность не выделять частные данные, только что используемые этой реализацией ObjectOutputStream.
- ObjectOutputStream (OutputStream out): создает ObjectOutputStream, который записывает в указанный OutputStream.
Methods:
- protected void annotateClass(Class cl) : Subclasses may implement this method to allow class data to be stored in the stream. By default this method does nothing. The corresponding method in ObjectInputStream is resolveClass. This method is called exactly once for each unique class in the stream. The class name and signature will have already been written to the stream. This method may make free use of the ObjectOutputStream to save any representation of the class it deems suitable (for example, the bytes of the class file). The resolveClass method in the corresponding subclass of ObjectInputStream must read and use any data or objects written by annotateClass.
Syntax :protected void annotateClass(Class cl) throws IOException Parameters: cl - the class to annotate custom data for Throws: IOException//Java program demonstrating ObjectOutputStream methods//illustrating annotateClass(Class<?> cl) methodimportjava.io.*;classObjectOutputStreamDemoextendsObjectOutputStream{publicObjectOutputStreamDemo(OutputStream out)throwsIOException{super(out);}publicstaticvoidmain(String[] args)throwsIOException,ClassNotFoundException{FileOutputStream fout =newFileOutputStream("file.txt");ObjectOutputStreamDemo oot =newObjectOutputStreamDemo(fout);Character c ="A";//illustrating annotateClass(Class<?> cl) methodoot.annotateClass(Character.class);//Write the specified object to the ObjectOutputStreamoot.writeObject(c);//flushing the streamoot.flush();//closing the streamoot.close();FileInputStream fin =newFileInputStream("file.txt");ObjectInputStream oit =newObjectInputStream(fin);System.out.print(oit.readObject());oit.close();}}Output :
A
- protected void annotateProxyClass(Class cl) : Subclasses may implement this method to store custom data in the stream along with descriptors for dynamic proxy classes.This method is called exactly once for each unique proxy class descriptor in the stream. The default implementation of this method in ObjectOutputStream does nothing.
The corresponding method in ObjectInputStream is resolveProxyClass. For a given subclass of ObjectOutputStream that overrides this method, the resolveProxyClass method in the corresponding subclass of ObjectInputStream must read any data or objects written by annotateProxyClass.
Syntax :protected void annotateProxyClass(Class cl) throws IOException Parameters: cl - the proxy class to annotate custom data for Throws: IOException//Java program demonstrating ObjectOutputStream//illustrating annotateProxyClass(Class<?> cl) methodimportjava.io.*;classObjectOutputStreamDemoextendsObjectOutputStream{publicObjectOutputStreamDemo(OutputStream out)throwsIOException{super(out);}publicstaticvoidmain(String[] args)throwsIOException,ClassNotFoundException{FileOutputStream fout =newFileOutputStream("file.txt");ObjectOutputStreamDemo oot =newObjectOutputStreamDemo(fout);Character c ="A";//illustrating annotateProxyClass(Class<?> cl) methodoot.annotateProxyClass(Character.class);//Write the specified object to the ObjectOutputStreamoot.writeObject(c);//flushingoot.flush();//closing the streamoot.close();FileInputStream fin =newFileInputStream("file.txt");ObjectInputStream oit =newObjectInputStream(fin);System.out.print(oit.readObject());oit.close();}}Output :
A
- void close() : Closes the stream.This method must be called to release any resources associated with the stream.
Syntax :public void close() throws IOException Throws: IOException//Java program demonstrating ObjectOutputStream//illustrating close() methodimportjava.io.*;classObjectOutputStreamDemo{publicstaticvoidmain(String[] args)throwsIOException{FileOutputStream fout =newFileOutputStream("file.txt");ObjectOutputStream oot =newObjectOutputStream(fout);oot.write(3);//illustrating close()oot.close();FileInputStream fin =newFileInputStream("file.txt");ObjectInputStream oit =newObjectInputStream(fin);System.out.println(oit.read());oit.close();}}Output :
3
- void defaultWriteObject() : Write the non-static and non-transient fields of the current class to this stream. This may only be called from the writeObject method of the class being serialized. It will throw the NotActiveException if it is called otherwise.
Syntax :public void defaultWriteObject() throws IOException Throws: IOException//Java program demonstrating ObjectOutputStream//illustrating defaultWriteObject() methodimportjava.io.*;classObjectOutputStreamDemo{publicstaticvoidmain(String[] arg)throwsIOException,ClassNotFoundException{Character a ="A";FileOutputStream fout =newFileOutputStream("file.txt");ObjectOutputStream oot =newObjectOutputStream(fout);oot.writeChar(a);oot.flush();// close the streamoot.close();FileInputStream fin =newFileInputStream("file.txt");ObjectInputStream oit =newObjectInputStream(fin);// reading the characterSystem.out.println(oit.readChar());}}classdemoimplementsSerializable{String s ="GeeksfoGeeks";privatevoidwriteObject(ObjectOutputStream out)throwsIOException, ClassNotFoundException{//demonstrating defaultWriteObject()out.defaultWriteObject();}}}Output :
A
- protected void drain() : Drain any buffered data in ObjectOutputStream. Similar to flush but does not propagate the flush to the underlying stream.
Syntax :protected void drain() throws IOException Throws: IOException//Java program demonstrating ObjectOutputStream methods//illustrating drain() methodimportjava.io.*;classObjectOutputStreamDemoextendsObjectOutputStream{publicObjectOutputStreamDemo(OutputStream out)throwsIOException{super(out);}publicstaticvoidmain(String[] arg)throwsIOException,ClassNotFoundException{FileOutputStream fout =newFileOutputStream("file.txt");ObjectOutputStream oot =newObjectOutputStream(fout);ObjectOutputStreamDemo obj =newObjectOutputStreamDemo(oot);//illustrating drain()obj.drain();//closing the underlying streamoot.close();fout.close();}} - protected boolean enableReplaceObject(boolean enable) : Enable the stream to do replacement of objects in the stream.When enabled, the replaceObject method is called for every object being serialized.
If enable is true, and there is a security manager installed, this method first calls the security manager’s checkPermission method with a SerializablePermission(“enableSubstitution”) permission to ensure it’s ok to enable the stream to do replacement of objects in the stream.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 program demonstrating ObjectOutputStream//illustrating enableReplaceObject methodimportjava.io.*;classObjectOutputStreamDemoextendsObjectOutputStream{publicObjectOutputStreamDemo(OutputStream out)throwsIOException{super(out);}publicstaticvoidmain(String[] args)throwsIOException,ClassNotFoundException{FileOutputStream fout =newFileOutputStream("file.txt");ObjectOutputStreamDemo oot =newObjectOutputStreamDemo(fout);Character c ="A";//illustrating enableReplaceObject methodSystem.out.println(oot.enableReplaceObject(true));//Write the specified object to the ObjectOutputStreamoot.writeObject(c);//flushingoot.flush();//closing the streamoot.close();FileInputStream fin =newFileInputStream("file.txt");ObjectInputStream oit =newObjectInputStream(fin);System.out.print(oit.readObject());oit.close();}}Output :
false A
- ObjectOutputStream.PutField putFields() : Retrieve the object used to buffer persistent fields to be written to the stream.The fields will be written to the stream when writeFields method is called.
Syntax :public ObjectOutputStream.PutField putFields() throws IOException Returns: an instance of the class Putfield that holds the serializable fields Throws: IOException//Java program demonstrating ObjectOutputStream//illustating PutField methodimportjava.io.*;classObjectOutputStreamDemo{publicstaticvoidmain(String[] arg)throwsIOException,ClassNotFoundException{Character a ="A";FileOutputStream fout =newFileOutputStream("file.txt");ObjectOutputStream oot =newObjectOutputStream(fout);oot.writeChar(a);oot.flush();// close the streamoot.close();FileInputStream fin =newFileInputStream("file.txt");ObjectInputStream oit =newObjectInputStream(fin);// reading the characterSystem.out.println(oit.readChar());}}classdemoimplementsSerializable{privatevoidwriteObject(ObjectOutputStream out)throwsIOException, ClassNotFoundException{// Retrieve the object used to buffer// persistent fields to be written to the streamObjectOutputStream.PutField fields = out.putFields();}}Output :
A
- protected Object replaceObject(Object obj) : This method will allow trusted subclasses of ObjectOutputStream to substitute one object for another during serialization.Replacing objects is disabled until enableReplaceObject is called. The enableReplaceObject method checks that the stream requesting to do replacement can be trusted. The first occurrence of each object written into the serialization stream is passed to replaceObject. Subsequent references to the object are replaced by the object returned by the original call to replaceObject. To ensure that the private state of objects is not unintentionally exposed, only trusted streams may use replaceObject.
This method is called only once when each object is first encountered. All subsequent references to the object will be redirected to the new object. This method should return the object to be substituted or the original object.Null can be returned as the object to be substituted, but may cause NullReferenceException in classes that contain references to the original object since they may be expecting an object instead of 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 program demonstrating ObjectOutputStream//illustrating replaceObject methodimportjava.io.*;classObjectOutputStreamDemoextendsObjectOutputStream{publicObjectOutputStreamDemo(OutputStream out)throwsIOException{super(out);}publicstaticvoidmain(String[] args)throwsIOException,ClassNotFoundException{FileOutputStream fout =newFileOutputStream("file.txt");ObjectOutputStreamDemo oot =newObjectOutputStreamDemo(fout);String a ="forGeeks";String b ="Geeks";//Write the specified object to the ObjectOutputStreamoot.writeObject(a);//flushing the streamoot.flush();oot.enableReplaceObject(true);//illustrating replaceObjectSystem.out.print(oot.replaceObject(b));//closing the streamoot.close();FileInputStream fin =newFileInputStream("file.txt");ObjectInputStream oit =newObjectInputStream(fin);System.out.print(oit.readObject());oit.close();}}Output :
GeeksforGeeks
- void useProtocolVersion(int version) : Specify stream protocol version to use when writing the stream.This routine provides a hook to enable the current version of Serialization to write in a format that is backwards compatible to a previous version of the stream format.
Every effort will be made to avoid introducing additional backwards incompatibilities; however, sometimes there is no other alternative.
Syntax :public void useProtocolVersion(int version) throws IOException Parameters: version - use ProtocolVersion from java.io.ObjectStreamConstants. Throws: IllegalStateException IllegalArgumentException IOException//Java program demonstrating ObjectOutputStream//illustrating useProtocolVersion() methodimportjava.io.*;classObjectOutputStreamDemoextendsObjectOutputStream{publicObjectOutputStreamDemo(OutputStream out)throwsIOException{super(out);}publicstaticvoidmain(String[] args)throwsIOException,ClassNotFoundException{FileOutputStream fout =newFileOutputStream("file.txt");ObjectOutputStreamDemo oot =newObjectOutputStreamDemo(fout);String a ="forGeeks";String b ="Geeks";//illustrating useProtocolVersion()oot.useProtocolVersion(ObjectStreamConstants.PROTOCOL_VERSION_2);//Write the specified object to the ObjectOutputStreamoot.writeObject(b);oot.writeObject(a);//flushing the streamoot.flush();oot.close();FileInputStream fin =newFileInputStream("file.txt");ObjectInputStream oit =newObjectInputStream(fin);System.out.print(oit.readObject());System.out.print(oit.readObject());oit.close();}}Output :
GeeksforGeeks
Next Article : Java.io.ObjectOutputStream Class in Java | Set 2
This article is contributed by Nishant Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGe