Nearby lessons

57 of 125

Java - IO Streams

📌 What You Will Learn
  • 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:

PointByte streamsCharacter streams
Read/write whatBytes (images, videos, any file)Characters (text files)
Parent classesInputStream / OutputStreamReader / Writer
ExamplesFileInputStream, FileOutputStreamFileReader, FileWriter
Best forPictures, songs, zip files.txt, .csv, .html documents
In simple words: Byte streams handle raw bytes and character streams handle text. Use InputStream/OutputStream for images and videos, and Reader/Writer for .txt and .csv files.

IO Class Map — Memory Aid

Remember: text uses Reader/Writer, binary uses InputStream/OutputStream, whole objects use Object streams. Everything is under java.io.

Example02
Loading editor…

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.

Example03
Loading editor…

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.

Example04
Loading editor…
📝 Key Takeaways
  • 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.

🧠 Test Your Knowledge

1 Questions
Progress: 0 / 1

Finished this lesson?

Mark it as complete to track your progress and see technology completion stats.