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
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
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
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