File I/O
- A file is used to persist data (save it to disk and then re-read it later).
- Java uses the concept of streams.
- A
stream
is a flow of data from a source to a destination.
- Historically, the idea comes from UNIX.
- A program can read from a stream and write to a stream without necessarily
knowing exactly what is on the other side.
-
There are 2 basic types of file streams:
- text files - character data, made of up of strings. Keyboard and GUI input is also string-based data. Reading and writing is done with character-based streams.
- binary files - native-format data, stored as 1's and 0's not as characters. Reading and writing is done with byte-based streams.
- In Java, an
input stream
reads bytes and a
reader
reads characters.
- Also an
output stream
writes bytes and a
writer
write characters.
- Output streams (or writers) are paired with input streams (or readers)
and are called
brothers.
- On a UNIX system, System.out is standard out,
System.err is standard error, and System.in is standard in.
- There are many types of streams and readers, but since they are all part of the same class hierarchy, the work in very much the same way.
- The super classes are InputStream and Reader.
- The stream you wish to read from is opened when you instantiate the object (with new).
- You can use the close() method to close the stream.
- The read() method can be used to read the data.
- It has a number of forms, but they all do a
blocking read,
which means the read waits until all the data you have requested is read.
It will block until the buffer is filled or the end of the stream is
encountered.
- This is not usually a limitation because the read can be placed in its
own thread so the program can do other tasks.
- A call to read() will return the number of characters (or bytes) read or
a -1 if it is at the end of the stream.
- The -1 is historical (EOF from C++), but the Java way to handle it is by
catching and processing an EOFException.
- The skip() method can be used to skip over data in the stream before
reading.
- Other helpful classes include Path and File.
- Pipes are manipulated with the PipedOutputStream and PipedInputStream classes.