Java Reference
In-Depth Information
Display 10.15
Some Methods in the Class ObjectInputStream (part 3 of 3)
public String readUTF() throws IOException
Reads a String value from the input stream and returns that String value. If readUTF tries
to read a value from the file and that value was not written using the method writeUTF of the
class ObjectOutputStream (or written in some equivalent way), then problems will occur. If an
attempt is made to read beyond the end of the file, an EOFException is thrown.
Object readObject() throws ClassNotFoundException, IOException
Reads an object from the input stream. The object read should have been written using
writeObject of the class ObjectOutputStream . Throws a ClassNotFoundException if
a serialized object cannot be found. If an attempt is made to read beyond the end of the file, an
EOFException is thrown. May throw various other IOExceptions .
public int skipBytes( int n) throws IOException
Skips n bytes.
public void close() throws IOException
Closes the stream's connection to a file.
reading
multiple
types
ObjectInputStream allows you to read input values of different types from the same
file. So, you may read a combination of, for example, int values, double values, and
String values. However, if the next data item in the file is not of the type expected by
the reading method, the result is likely to be a mess. For example, if your program writes
an integer using writeInt , then any program that reads that integer should read it using
readInt . If you instead use readLong or readDouble , your program will misbehave.
Note that, as illustrated in Display 10.16, you close a binary input stream in the
same way that you close all the other I/O streams we have seen.
closing a
binary file
Self-Test Exercises
32. Write code to open the binary fi le named someStuff and connect it to an
ObjectInputStream object named inputThing so it is ready for reading.
33. Give a statement that will read a number of type double from the fi le
someStuff and place the value in a variable named number . Use the stream
inputThing that you created in Self-Test Exercise 32. (Assume the fi rst thing
written to the fi le was written using the method writeDouble of the class
ObjectOutputStream and assume number is of type double .)
34. Give a statement that will close the stream inputThing created in Self-Test
Exercise 32.
35. Can one program write a number to a fi le using writeInt and then have
another program read that number using readLong ? Can a program read that
number using readDouble ?
36. Can you use readUTF to read a string from a text fi le?
 
 
Search WWH ::




Custom Search