23.07.2013 Views

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>Java</strong> I/O<br />

are not serializable, then the container won't be, either. Most Sun-supplied components are<br />

serializable, but third-party components often aren't.<br />

11.5.1.2 Problem 2: Missing a no-argument constructor in superclass<br />

The second common problem that prevents a serializable class from being deserialized is that<br />

a superclass of the class is not serializable and does not contain a no-argument constructor.<br />

java.lang.Object does not implement Serializable, so all classes have at least one<br />

superclass that's not serializable. When an object is deserialized, the no-argument constructor<br />

of the closest superclass that does not implement Serializable is invoked to establish the<br />

state of the object's nonserializable superclasses. If that class does not have a no-argument<br />

constructor, then the object cannot be deserialized. For example, consider the<br />

java.io.ZipFile class introduced in Chapter 9. It does not implement Serializable:<br />

public class ZipFile extends Object implements java.util.zip.ZipConstants<br />

Furthermore, it has only these two constructors, both of which take arguments:<br />

public ZipFile(String filename) throws <strong>IO</strong>Exception<br />

public ZipFile(File file) throws ZipException, <strong>IO</strong>Exception<br />

Suppose you want to subclass it to allow the class to be serialized, as shown in Example 11.2.<br />

Example 11.2. A SerializableZipFileNot<br />

import java.io.*;<br />

import java.util.zip.*;<br />

public class SerializableZipFileNot extends ZipFile<br />

implements Serializable {<br />

public SerializableZipFileNot(String filename) throws <strong>IO</strong>Exception {<br />

super(filename);<br />

}<br />

public SerializableZipFileNot(File file) throws <strong>IO</strong>Exception {<br />

super(file);<br />

}<br />

public static void main(String[] args) {<br />

try {<br />

SerializableZipFileNot szf = new SerializableZipFileNot(args[0]);<br />

ByteArrayOutputStream bout = new ByteArrayOutputStream();<br />

ObjectOutputStream oout = new ObjectOutputStream(bout);<br />

oout.writeObject(szf);<br />

oout.close();<br />

System.out.println("Wrote object!");<br />

ByteArrayInputStream bin = new<br />

ByteArrayInputStream(bout.toByteArray());<br />

ObjectInputStream oin = new ObjectInputStream(bin);<br />

Object o = oin.readObject();<br />

System.out.println("Read object!");<br />

}<br />

catch (Exception e) {e.printStackTrace();}<br />

}<br />

245

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!