Wednesday, October 28, 2009

Persisting Objects with Java Streams




I l@ve RuBoard









Persisting Objects with Java Streams


ObjectOutputStream 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.



>>> from java.io import ObjectOutputStream, FileOutputStream

Create an instance of ObjectOutputStream, passing the constructor a new instance of FileOutputStream.



>>> oos = ObjectOutputStream(FileOutputStream("c:\\dat\\out.bin"))

Define a simple class.



>>> class MyClass:
... def __init__(self):
... self.a = "a"
...

Create an instance of the class.



>>> object = MyClass()

Write the instance to the output stream with the writeObject() method.



>>> oos.writeObject(object)
>>> oos.close() #From here

Now we can use ObjectInputStream to read the object back. Import ObjectInputStream and FileInputStream from package java.io.



>>> from java.io import ObjectInputStream, FileInputStream

Create an instance of ObjectInputStream.



>>> ois = ObjectInputStream(FileInputStream("c:\\dat\\out.bin"))

Read the object from the stream.



>>> object2 = ois.readObject()

Show that the attribute of object2 is the same as the attribute of object but that object and object2 aren't the same.



>>> print "The a attribute of object 2 is " + object2.a
>>> print "Are object and object2 the same? " + `(object is object2)`

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