ActiveState Powered by ActiveState

Recipe 252131: Pickle objects under jython


Using the pickle module under jython is a rather slow method for storing data. Using the ObjectOutputStream speeds it up. You can save and restore objects (jython and java) with these functions.

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
from java import io
def saveObject(x,fname="jython.bin"):
    outs=io.ObjectOutputStream(io.FileOutputStream(fname))
    outs.writeObject(x)
    outs.close()
def loadObject(fname="jython.bin"):
    ins=io.ObjectInputStream(io.FileInputStream(fname))
    x=ins.readObject()
    ins.close()
    return x


x={1:1,'two':"2",'three':[1,2,3]}
saveObject(x)
y=loadObject()
print y

Discussion

The objects have to implement the Serializable interface. Most of jython's classes do. It is also very useful together with the JNumeric package.

Comments

  1. 1. At 6:45 a.m. on 21 feb 2004, eoghan murray said:

    PythonObjectInputStream. Should the Input Stream be a PythonObjectInputStream from org.python.util?

    I would love to see a recipe on using Java's RandomAccessFile with Jython

    Eoghan

Sign in to comment