I would like to make a summary of what I learned about the java.io package. It's something I've an hard time with so hopefully some other people will chime in as well.
1. Writer/Readers vs OutputStream/InputStream
For reading or writing to a file there is two group of abstract classes from which the others descend. The streams,
InputStream and
OutputStream are used for
binary data, while the
Reader and
Writer are used to deal with
characters. Readers and Writers use streams internally, but make working with characters easier.
Low level vs High Level
We can divide the classes used to read / write data from files into two groups.
- Low level: FileInputStream, FileOutputStream, FileReader, FileWriter
- High level: BufferedInputStream, BufferedReader, ObjectInputStream and their accompanying output classes.
So we have this diagram for input which all have accompanying output class:
I think that's all the ones we need to know for the exam, but I'm not sure.
The
low level take a
file or a
string as constructor argument. while the
high level take another
input stream. This means that to read from a file we will have a combination of high and low level
:
However it also means that we can have non-sensical things like this :
The buffered classes
Those classes are for reading data in chunks instead of a per byte basis. They greatly improve performance.
( Personal rant: While
java designers could have abstracted this low level mess, they decided it would be more in line with the rest of the language if the programming interface was badly designed. I'm serious, this is monstruosity. Hopefully I'll learn they fixed it in the chapter on java.nio)
ObjectOutputStream
Used for serialization of objects. What is should be known is this:
- Object fields can be marked as transient to not be serialized.
- Static fields are not part of the object, thus not serialized.
- Constructor and static initialization are not called upon deserialization.
- Serialization will try to serialize child objects, thus those child objects must also be serializable.