ObjectOutputStream записва примитивни типове данни и графики на Java обекти в OutputStream. Обектите могат да бъдат прочетени (реконституирани) с помощта на ObjectInputStream. Постоянното съхранение на обекти може да бъде осъществено чрез използване на файл за потока.
- Само обекти, които поддържат интерфейса java.io.Serializable, могат да се записват в потоци. Класът на всеки сериализиращ се обект е кодиран, включително името на класа и подписа на класа, стойностите на полетата и масивите на обекта и затварянето на всички други обекти, посочени от първоначалните обекти.
- Java ObjectOutputStream често се използва заедно с Java ObjectInputStream. ObjectOutputStream се използва за запис на Java обектите, а ObjectInputStream се използва за повторно четене на обектите.
Конструктори:
Методи:
java тип преобразуване и кастинг
Syntax : protected void annotateClass(Class cl) throws IOException Parameters: cl - the class to annotate custom data for Throws: IOExceptionJava
//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(); } }
Изход:
A
Съответният метод в ObjectInputStream е resolveProxyClass. За даден подклас на ObjectOutputStream, който замества този метод, методът resolveProxyClass в съответния подклас на ObjectInputStream трябва да прочете всички данни или обекти, записани от annotateProxyClass.
Syntax : protected void annotateProxyClass(Class cl) throws IOException Parameters: cl - the proxy class to annotate custom data for Throws: IOExceptionJava
//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(); } }
Изход:
A
Syntax : public void close() throws IOException Throws: IOExceptionJava
//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(); } }
3
Syntax : public void defaultWriteObject() throws IOException Throws: IOExceptionJava
//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(); } } }
Изход:
A
Syntax : protected void drain() throws IOException Throws: IOExceptionJava
//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(); } }
Ако enable е true и има инсталиран мениджър на сигурността, този метод първо извиква метода checkPermission на мениджъра на сигурността с разрешение SerializablePermission('enableSubstitution'), за да се увери, че е добре да се разреши на потока да извършва замяна на обекти в потока.
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: SecurityExceptionJava
//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(); } }
Изход:
false A
Syntax : public ObjectOutputStream.PutField putFields() throws IOException Returns: an instance of the class Putfield that holds the serializable fields Throws: IOExceptionJava
//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(); } }
Изход:
runas в powershell
A
Този метод се извиква само веднъж, когато всеки обект се срещне за първи път. Всички последващи препратки към обекта ще бъдат пренасочени към новия обект. Този метод трябва да върне обекта, който трябва да бъде заменен, или оригиналния обект.
Null може да бъде върнат като обект, който трябва да бъде заместен, но може да причини NullReferenceException в класове, които съдържат препратки към оригиналния обект, тъй като те може да очакват обект вместо 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: IOExceptionJava
//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(); } }
Изход:
GeeksforGeeks
Ще бъдат положени всички усилия, за да се избегне въвеждането на допълнителни обратни несъвместимости; но понякога няма друга алтернатива.
Syntax : public void useProtocolVersion(int version) throws IOException Parameters: version - use ProtocolVersion from java.io.ObjectStreamConstants. Throws: IllegalStateException IllegalArgumentException IOExceptionJava
//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(); } }
Изход:
GeeksforGeeks
Следваща статия: Java.io.ObjectOutputStream Клас в Java | Комплект 2
java system.out.println