Java File Handling with FileReader and FileWriter – Complete Guide


Learn Java File I/O using FileReader and FileWriter to read from and write to files, including examples, best practices, and exception handling.

File Handling in Java (FileReader, FileWriter) – Complete Detailed Tutorial

Java provides classes to read and write files in character format:

  1. FileReader – to read characters from a file
  2. FileWriter – to write characters to a file

They are part of java.io package.

1. FileReader Class

  1. Reads characters from a file
  2. Constructor: FileReader(String fileName)
  3. Common methods: read(), close()
  4. Throws IOException

Example – Reading a File


import java.io.FileReader;
import java.io.IOException;

public class Main {
public static void main(String[] args) {
try (FileReader fr = new FileReader("input.txt")) {
int i;
while ((i = fr.read()) != -1) {
System.out.print((char) i);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Explanation:

  1. read() returns ASCII value of character or -1 at end of file
  2. try-with-resources ensures automatic closing of file

2. FileWriter Class

  1. Writes characters to a file
  2. Constructor: FileWriter(String fileName, boolean append)
  3. append = true → append to existing file
  4. append = false → overwrite file

Example – Writing to a File


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

public class Main {
public static void main(String[] args) {
try (FileWriter fw = new FileWriter("output.txt")) {
fw.write("Hello, FileWriter!\n");
fw.write("Java File Handling Example.");
} catch (IOException e) {
e.printStackTrace();
}
}
}

Explanation:

  1. write() writes characters or strings
  2. File is automatically closed using try-with-resources

3. FileReader + FileWriter Example

  1. Copy contents from one file to another

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class Main {
public static void main(String[] args) {
try (FileReader fr = new FileReader("input.txt");
FileWriter fw = new FileWriter("copy.txt")) {

int i;
while ((i = fr.read()) != -1) {
fw.write(i);
}

System.out.println("File copied successfully!");
} catch (IOException e) {
e.printStackTrace();
}
}
}

Explanation:

  1. Reads one character at a time
  2. Writes it to another file
  3. Demonstrates basic file I/O operations

4. Key Points

  1. FileReader/FileWriter are for character-based files
  2. For binary files, use FileInputStream/FileOutputStream
  3. Always handle IOException
  4. Prefer try-with-resources to automatically close files
  5. append = true to preserve existing file content

5. Summary

  1. FileReader: read characters
  2. FileWriter: write characters
  3. Try-with-resources: best practice for file handling
  4. Can combine FileReader + FileWriter to copy files or modify content
  5. Core part of Java I/O Streams