CodeBlanks Logo Icon CodeBlanks

FileReader and FileWriter

Learn to read and write text with FileReader and FileWriter.

Writing with FileWriter

The FileWriter class writes character by character. FileWriter w = new FileWriter("a.txt"); opens the file in write mode; it creates the file if missing, and truncates if it exists. w.write("Hello"); writes the text, w.close(); releases the resource.

FileWriter uses the system encoding by default. For correct Turkish characters, prefer new FileWriter("a.txt", StandardCharsets.UTF_8). You must call close() after writing; otherwise data may not reach disk.

Reading with FileReader

FileReader reads character by character. FileReader r = new FileReader("a.txt"); opens the file in read mode. r.read() returns the Unicode code of one character per call; at end of file it returns -1.

Reading single characters is inefficient; you usually wrap it in a BufferedReader. But for small files, direct FileReader is fine. After reading, r.close() is required.

Practice Write to a file with FileWriter

Import java.io.FileWriter and java.io.IOException. Add throws IOException to main. Create a FileWriter w = new FileWriter("hello.txt");, call w.write("Hello file");, close with w.close();. Finally print System.out.println("Written");.

Starter code

Main.java
import java.io.FileWriter;
import java.io.IOException;

public class Main {
    public static void main(String[] args) throws IOException {
        // Create FileWriter, write, close

        // Print Written

    }
}

Sample solution

Main.java
import java.io.FileWriter;
import java.io.IOException;

public class Main {
    public static void main(String[] args) throws IOException {
        FileWriter w = new FileWriter("hello.txt");
        w.write("Hello file");
        w.close();
        System.out.println("Written");
    }
}

Expected output

Written

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the write call

Question
FileWriter w = new FileWriter("a.txt");
w.____("Hello");
w.close();
Answer
FileWriter w = new FileWriter("a.txt");
w.write("Hello");
w.close();

Explanation: The write method writes text to the file.

2 What does FileReader.read() return at end of file?

  • -1 Correct answer
  • null
  • 0
  • An empty string

Explanation: read() returns -1 at end of file; this is used in loop conditions.

3 Match the Reader/Writer classes

Term Meaning
FileWriter Writes character by character
FileReader Reads character by character
write() Writes text to the file
read() Reads one character's code

All lessons in Intermediate