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
JCode Cell
1import java.io.*;
2 
3class WriteFile {
4 public static void main(String[] args) throws Exception {
5 FileWriter fw = new FileWriter("notes.txt");
6 fw.write("First line of my notes.\n");
7 fw.write("Second line of my notes.");
8 fw.close(); // always close - saves data to the file
9 System.out.println("File written successfully");
10 }
11}
Output
File written successfully

Reading a File — Character by Character

Example02
JCode Cell
1import java.io.*;
2 
3class ReadFile {
4 public static void main(String[] args) throws Exception {
5 FileReader fr = new FileReader("notes.txt");
6 int ch;
7 while ((ch = fr.read()) != -1) { // -1 means end of file
8 System.out.print((char) ch);
9 }
10 fr.close();
11 }
12}
Output
First line of my notes. Second line of my notes.

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
JCode Cell
1import java.io.*;
2 
3class ReadLine {
4 public static void main(String[] args) throws Exception {
5 BufferedReader br = new BufferedReader(new FileReader("notes.txt"));
6 String line;
7 while ((line = br.readLine()) != null) {
8 System.out.println("LINE: " + line);
9 }
10 br.close();
11 }
12}
Output
LINE: First line of my notes. LINE: Second line of my notes.

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
JCode Cell
1import java.io.*;
2 
3class CopyImage {
4 public static void main(String[] args) throws Exception {
5 FileInputStream in = new FileInputStream("photo.jpg");
6 FileOutputStream out = new FileOutputStream("photo_copy.jpg");
7 int b;
8 while ((b = in.read()) != -1) {
9 out.write(b);
10 }
11 in.close();
12 out.close();
13 System.out.println("Image copied");
14 }
15}
📝 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