Nearby lessons
55 of 125Java - 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
Reading a File — Character by Character
Example02
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
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
📝 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 QuestionsProgress: 0 / 1