Nearby lessons
57 of 125Java - IO Streams
- What a stream is and how data flows
- Byte streams vs character streams
- Reading and writing text files easily
- The modern File methods and Scanner input
- Serialization — saving an object to a file
IO Streams is a core concept of the Java language. This lesson explains What is a Stream?, IO Class Map — Memory Aid and The Stream Family Tree with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.
What is a Stream?
A stream is a flow of data. It is like a pipe: data flows through it, from a source to a destination.
- Input stream — brings data into the program (e.g., reading from keyboard or a file).
- Output stream — carries data out of the program (e.g., writing to a file or the screen).
In Java, all input/output (IO) classes live in the java.io package. The two big families are byte streams and character streams:
| Point | Byte streams | Character streams |
|---|---|---|
| Read/write what | Bytes (images, videos, any file) | Characters (text files) |
| Parent classes | InputStream / OutputStream | Reader / Writer |
| Examples | FileInputStream, FileOutputStream | FileReader, FileWriter |
| Best for | Pictures, songs, zip files | .txt, .csv, .html documents |
IO Class Map — Memory Aid
Remember: text uses Reader/Writer, binary uses InputStream/OutputStream, whole objects use Object streams. Everything is under java.io.
The Stream Family Tree
All IO classes fit a neat family tree. Learn the parents, and every child makes sense:
InputStream/OutputStream handle bytes (images, videos). Reader/Writer handle characters (text). ObjectInput/ObjectOutput handle whole objects (serialization). The Buffered* versions make IO faster by reading/writing in chunks.
RandomAccessFile — Read and Write Anywhere
A RandomAccessFile can both read and write, and can jump to any position (using a pointer). You choose the mode: "r" for read only, "rw" for read and write.
- A stream is a flow of data: input brings data in, output sends it out.
- Byte streams (InputStream/OutputStream) for images/videos; character streams (Reader/Writer) for text.
- Wrap FileReader in BufferedReader to read text line by line.
- Scanner is the simplest way to read input from the keyboard.
- The File class gives file information; it does not read data.
- Serialization saves objects to files; transient fields are not saved.
- Always close streams — or better, use try-with-resources.