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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

}<br />

}<br />

Vector v = (Vector) oin.readObject();<br />

Enumeration e = v.elements();<br />

while (e.hasMoreElements()) {<br />

System.out.println(e.nextElement());<br />

}<br />

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

You may argue with my choice of name here; ExternalizableVector may seem more<br />

accurate. However, from the perspective of a programmer using a class, it doesn't matter<br />

whether a class is serializable or externalizable. In either case, instances of the class are<br />

merely passed to the writeObject() method of an object output stream or read by the<br />

readObject() method of an object input stream. The difference between Serializable and<br />

Externalizable is hidden from the end user.<br />

The writeExternal() method first writes capacityIncrement and elementCount onto the<br />

stream using writeInt(). It then loops through all the elements in the vector, testing each<br />

one with instanceof to see whether or not it's serializable. If the element is serializable, it's<br />

written with writeObject(); otherwise, null is written instead. The readExternal()<br />

method simply reads in the data and sets the appropriate fields in Vector.<br />

capacityIncrement is read first, then elementCount. The elementData array was not<br />

directly written onto the output in writeExternal(); instead, its individual elements were<br />

written. Thus, a new elementData array is created with length elementCount. Finally, the<br />

individual elements are read out and stored in elementData in the same order they were<br />

written.<br />

The main() method tests the program by serializing and deserializing a<br />

SerializableVector that contains assorted serializable and nonserializable elements. Its<br />

output is:<br />

D:\JAVA>java SerializableVector<br />

Element 1<br />

9<br />

http://www.oreilly.com/<br />

null<br />

Element 1<br />

9<br />

http://www.oreilly.com/<br />

Other schemes are possible and might be useful in some circumstances. Since elementData<br />

itself isn't stored but only recreated from its length, one obvious possibility is to omit the<br />

nonserializable elements when writing the vector and to adjust the elementCount<br />

accordingly. For example:<br />

public void writeExternal(ObjectOutput out) throws <strong>IO</strong>Exception {<br />

out.writeInt(capacityIncrement);<br />

int numSerializable = 0;<br />

for (int i = 0; i < elementCount; i++) {<br />

if (elementData[i] instanceof Serializable) {<br />

numSerializable++;<br />

}<br />

}<br />

259

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

Saved successfully!

Ooh no, something went wrong!