How to Use FileWriter in Java: Simple Guide with Examples
Use
FileWriter in Java to write characters to a file by creating a FileWriter object with the file path, then calling write() to add text. Always close the writer with close() or use try-with-resources to avoid resource leaks.Syntax
The basic syntax to use FileWriter is:
FileWriter writer = new FileWriter(String filePath);- creates a writer for the file atfilePath.writer.write(String text);- writes the given text to the file.writer.close();- closes the writer and releases resources.
You can also use try-with-resources to automatically close the writer.
java
FileWriter writer = new FileWriter("filename.txt"); writer.write("Hello, world!"); writer.close();
Example
This example shows how to write a simple string to a file named output.txt using FileWriter with try-with-resources to ensure the file is properly closed.
java
import java.io.FileWriter; import java.io.IOException; public class FileWriterExample { public static void main(String[] args) { String text = "Hello, FileWriter!"; try (FileWriter writer = new FileWriter("output.txt")) { writer.write(text); System.out.println("Text written to output.txt successfully."); } catch (IOException e) { System.out.println("An error occurred: " + e.getMessage()); } } }
Output
Text written to output.txt successfully.
Common Pitfalls
Common mistakes when using FileWriter include:
- Not closing the writer, which can cause data loss or resource leaks.
- Overwriting files unintentionally because
FileWriterby default overwrites existing files. - Not handling
IOException, which is required when working with files.
To append to a file instead of overwriting, use the constructor with a second boolean parameter true.
java
/* Wrong way: Not closing the writer */ FileWriter writer = new FileWriter("file.txt"); writer.write("Hello"); // writer.close() is missing /* Right way: Using try-with-resources to auto-close */ try (FileWriter writer2 = new FileWriter("file.txt", true)) { writer2.write("Appended text\n"); }
Quick Reference
Summary tips for using FileWriter:
- Use try-with-resources to auto-close the writer.
- Use
new FileWriter(file, true)to append instead of overwrite. - Always handle
IOException. - Write strings or characters with
write().
Key Takeaways
Always close FileWriter to avoid resource leaks, preferably with try-with-resources.
FileWriter overwrites files by default; use the append flag to add to files.
Handle IOException when working with FileWriter to catch file errors.
Use write() method to write text data to files.
Try-with-resources simplifies resource management and error handling.