Nearby lessons
55 of 125Java - Writing and Reading Files
- 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.
Reading a File — Character by Character
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.
Copying a Binary File (Image / Video)
For pictures, songs and videos, we must use byte streams, because character streams would corrupt the data.
- 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 QuestionsFinished this lesson?
Mark it as complete to track your progress and see technology completion stats.