How can an applet read a serialized object residing in the same directory?

Jon Wingfield

Normally when de-serializing from a file one would use a FileInputStream. However, in the case of an untrusted applet you can use an InputStream derived from the applet's document base URL. To load a file "myClass.ser" residing in the same directory use:

try {
    InputStream is = new URL(getDocumentBase(), "myClass.ser").openStream();
    ObjectInputStream ois = new ObjectInputStream(is);
    Object o = ois.readObject();
} catch (ClassNotFoundException cnfe) {
} catch (IOException ioe) {
A more general mechanism would be to use the static getResourceAsStream(...) method of ClassLoader. This searches for the resource along the application classpath and returns an InputStream to the resource. The serialized object file can now be either on the Web Server or bundled as part of the applet's jar archive. If the serialized file is not being changed by some other process then it would make sense to have it in the jar as this reduces the number of requests the applet needs to make to the server.

If de-serialization of objects is being used to reduce initialization time of your applet you could use the OBJECT attribute of the APPLET tag to specify a serialized version of the entire applet. However, care is needed if you use this feature. For additional info see http://java.sun.com/products/jdk/1.1/docs/guide/misc/applet.html.