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:
- FileReader – to read characters from a file
- FileWriter – to write characters to a file
They are part of java.io package.
1. FileReader Class
- Reads characters from a file
- Constructor:
FileReader(String fileName) - Common methods:
read(),close() - 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:
read()returns ASCII value of character or-1at end of filetry-with-resourcesensures automatic closing of file
2. FileWriter Class
- Writes characters to a file
- Constructor:
FileWriter(String fileName, boolean append) append = true→ append to existing fileappend = 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:
write()writes characters or strings- File is automatically closed using try-with-resources
3. FileReader + FileWriter Example
- 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:
- Reads one character at a time
- Writes it to another file
- Demonstrates basic file I/O operations
4. Key Points
- FileReader/FileWriter are for character-based files
- For binary files, use FileInputStream/FileOutputStream
- Always handle IOException
- Prefer try-with-resources to automatically close files
append = trueto preserve existing file content
5. Summary
- FileReader: read characters
- FileWriter: write characters
- Try-with-resources: best practice for file handling
- Can combine FileReader + FileWriter to copy files or modify content
- Core part of Java I/O Streams