I l@ve RuBoard |
Persisting Objects with Java StreamsObjectOutputStream writes out Java class instances (objects) to an output stream. It accomplishes for Java what the pickle module does for Python. Only Java instances that have the Serializable class (interface) as a base class (interface) can be serialized with ObjectOutputStream. All Jython objects (class instances, functions, dictionaries, lists) implement Serializable. Here's a short example. Import ObjectOutputStream and FileOutputStream from the java.io package.
Create an instance of ObjectOutputStream, passing the constructor a new instance of FileOutputStream.
Define a simple class.
Create an instance of the class.
Write the instance to the output stream with the writeObject() method.
Now we can use ObjectInputStream to read the object back. Import ObjectInputStream and FileInputStream from package java.io.
Create an instance of ObjectInputStream.
Read the object from the stream.
Show that the attribute of object2 is the same as the attribute of object but that object and object2 aren't the same.
As I said, object streams function a lot like the pickle module. As an exercise, modify the address book application from Chapter 8 to use object streams instead of pickle. |
I l@ve RuBoard |
No comments:
Post a Comment