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 />

To write an object onto a stream, you chain an object output stream to the stream, then pass<br />

the object to the object output stream's writeObject() method:<br />

public final void writeObject(Object o) throws <strong>IO</strong>Exception<br />

For example:<br />

try {<br />

Point p = new Point(34, 22);<br />

FileOutputStream fout = new FileOutputStream("point.ser");<br />

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

oout.writeObject(p);<br />

oout.close();<br />

}<br />

catch (Exception e) {System.err.println(e);}<br />

Later, the object can be read back using the readObject() method of the<br />

ObjectInputStream class:<br />

public final Object readObject()<br />

throws OptionalDataException, ClassNotFoundException,<br />

<strong>IO</strong>Exception<br />

For example:<br />

try {<br />

FileInputStream fin = new FileInputStream("point.ser");<br />

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

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

Point p = (Point) o;<br />

oin.close();<br />

}<br />

catch (Exception e) {System.err.println(e);}<br />

The reconstituted point has the same values as the original point. Its x is 34 and its y is 22, just<br />

like the Point object that was written. However, since readObject() is only declared to<br />

return an Object, you usually need to cast the deserialized object to a more specific type.<br />

Both writeObject() and readObject() throw <strong>IO</strong>Exception for all the usual reasons an I/O<br />

operation can fail (disk filling up, network connection being severed, etc.). The<br />

readObject() method also throws OptionalDataException if the stream doesn't appear to<br />

contain an object in the proper format or a ClassNotFoundException if a definition for the<br />

class of the object read from the input stream is not available in the current VM.<br />

11.3 How Object Serialization Works<br />

Objects possess state. This state is stored in the values of the nonstatic, nontransient fields of<br />

an object's class. Consider this TwoDPoint class:<br />

public class TwoDPoint {<br />

public double x;<br />

public double y;<br />

}<br />

239

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

Saved successfully!

Ooh no, something went wrong!