Many of the file handling methods throw exceptions.
The most common is an IOException, and indeed the others are all "types of"
IOExceptions (it will make more sense after we've covered inheritance).
IOExceptions are checked exceptions, i.e., it is
necessary to handle them or pass them up to the calling code.
Reading character files
These files store data in character format
The FileReader
class reads characters from a file.
The constructor takes a file name or File object argument, and may throw
a FileNotFoundException (which is a type of IOException)
The read method reads the next character from the file, returning it as
an int.
It may throw a IOException.
Returns -1 when the end of the file is reached
The close method closes the file (good habit there).
It may throw a IOException.
Serialization converts an object to a stream of bytes
An object is serializable only if its class implements the Serializable
interface.
Making instances of your classes serializable is easy.
You just add the implements Serializable clause to your class declaration like this:
public class MySerializableClass implements Serializable {
...
}
More about serialization after inheritance
The ObjectOutputStream
class writes objects to a file, in a serialized form.
The constructor takes a FileOutputStream object argument.
The ObjectInputStream
class reads serialized objects from a file.
The constructor takes a FileInputStream object argument.
These classes have methods for manipulating files of objects
Constructors initialize ObjectOutputStream and ObjectInputStream
objects.
They may throw an IOException.
writeObject writes an object to an ObjectOutputStream.
It may throw an IOException.
readObject reads an object from an ObjectInputStream.
It is necessary to type cast the objects that are read in.
It may throw an IOException or a ClassNotFoundException.
The end-of-file is recognized by catching the EOFException.
close closes a stream (and you should always do that when you've finished
using a stream, for many reasons).
It may throw an IOException.
What are the two basic types of data that Java can store in files?
What type of exception is thrown by many file operations?
A FileReader object reads characters from a file using its read method.
Write a program that reads the text file named as its command line
argument and prints it out to the screen. You must catch exceptions.
A BufferedReader object, which is created from a FileReader object, reads
characters from a file using its readLine method.
Write a program that reads the text file named as its command line
argument and prints it out to the screen. You must catch exceptions.
What does "serialization" do?
How do you make objects serializable?
When reading in serialized objects, why is it necessary to typecast them to the type of
object that you are reading?