Nearby lessons

55 of 125

Java - Writing and Reading Files

📌 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

Writing and Reading Files is a core concept of the Java language. This lesson explains Writing to a File, Reading a File — Character by Character and Reading a File — Line by Line (Recommended) with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

Writing to a File

FileWriter with one argument overwrites the file. Use new FileWriter("notes.txt", true) to append at the end instead.

Example01
Loading editor…

Reading a File — Character by Character

Example02
Loading editor…

Reading a File — Line by Line (Recommended)

Reading one character at a time is slow. Wrap the FileReader in a BufferedReader and read full lines — this is the standard approach.

In simple words: `readLine()` returns `null` when the file ends — that is the stop signal. Wrap a FileReader in a BufferedReader and keep reading lines until null, which is the standard way to read text files.
Example03
Loading editor…

Copying a Binary File (Image / Video)

For pictures, songs and videos, we must use byte streams, because character streams would corrupt the data.

Trainer's Note: Buffered streams make this much faster: wrap them like new BufferedInputStream(in). In real projects we also use try-with-resources so the files always close, as shown in the Exception Handling chapter.
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.