Java Tutorial/File/Introduction
Input Output
There are four types of streams: InputStream, OutputStream, Reader, and Writer.
- Reader. A stream to read characters.
- Writer. A stream to write characters.
- InputStream. A stream to read binary data.
- OutputStream. A stream to write binary data.
For better performance, use the buffered I/O classes: BufferedInputStream, BufferedOutputStream, BufferedReader, and BufferedWriter.
Reading from and writing to a stream dictate that you do so sequentially. The java.io.RandomAccessFile is for non-sequential operations.
For object serialization and deserialization, you can use the ObjectInputStream and ObjectOutputStream classes.
OutputStream
The OutputStream class defines three write method overloads, which are mirrors of the read method overloads in InputStream:
public void write (int b)
public void write (byte[] data)
public void write (byte[] data, int offset, int length)
- The first overload writes the lowest 8 bits of the integer b to this OutputStream.
- The second writes the content of a byte array to this OutputStream.
- The third overload writes length bytes of the data starting at offset offset.
- close() method closes the OutputStream.
- flush() method forces any buffered content to be written out to the sink.
Reading Binary Data
You use an InputStream to read binary data.
InputStream
|
+-- FileInputStream
|
+-- BufferedInputStream
- FileInputStream enables easy reading from a file.
- BufferedInputStream provides data buffering that improves performance.
- The ObjectInputStream class is used in object serialization.
Writing Binary Data
The OutputStream abstract class represents a stream for writing binary data
OutputStream
|
+--FileOutputStream
|
+--BufferedOutputStream.
|
+--ObjectOutputStream
- FileOutputStream provides a convenient way to write to a file.
- BufferedOutputStream provides better performance.
- ObjectOutputStream class plays an important role in object serialization.