FileWriter: Writing Characters to Text Files
What You'll Learn
You'll learn how to use FileWriter to write character data to text files, including creating new files and overwriting existing ones.
Understanding FileWriter
FileWriter is the character-based counterpart to FileOutputStream. While FileOutputStream writes raw bytes, FileWriter writes characters and handles the conversion to bytes using your system's default character encoding (or a specified encoding).
Think of FileWriter as a pen designed specifically for writing text. Just as you wouldn't use a pen meant for paper to etch metal, you use FileWriter for text content rather than binary data.
Creating FileWriter Instances
You can create a FileWriter in several ways:
New file or overwrite:
FileWriter writer = new FileWriter("output.txt");
This creates a new file if it doesn't exist, or overwrites the existing file completely.
Append mode:
FileWriter writer = new FileWriter("output.txt", true);
The second parameter (true) enables append mode—new content is added to the end of the existing file rather than replacing it.
Writing Character Data
FileWriter provides the write() methods you learned from the Writer class:
FileWriter writer = new FileWriter("greeting.txt");
writer.write("Hello, World!"); // Write a string
writer.write('\n'); // Write a single character
writer.close(); // Always close to flush data
Remember: you must call close() (or use try-with-resources) to ensure your data is actually written to disk.
Key Takeaway:
FileWriter simplifies writing text to files by handling character-to-byte encoding automatically; use the single-argument constructor to create/overwrite files, or pass true as the second argument to append to existing files.