The FileWriter class in Java is used to write character-based data to files.
It is part of the java.io package and provides methods to write text data to files.
FileWriter is particularly useful when you need to create or update a text file with custom content.
In this tutorial, we will cover:
- Basic Usage of FileWriter
- Appending Data to an Existing File
- Writing Characters and Strings
- Using BufferedWriter with FileWriter
- Handling Exceptions and Closing FileWriter
Let’s go through each section with examples.
1. Basic Usage of FileWriter
The FileWriter class has constructors to create a new file or to open an existing file for writing.
If the file does not exist, it creates it; if it does exist, it overwrites the file unless set otherwise.
Example 1: Writing a Simple Message to a File
import java.io.FileWriter; import java.io.IOException; public class BasicFileWriterExample { public static void main(String[] args) { try { // Create a FileWriter instance to write to "example.txt" FileWriter writer = new FileWriter("example.txt"); // Write a simple message writer.write("Hello, World!"); // Close the FileWriter writer.close(); System.out.println("Successfully wrote to the file."); } catch (IOException e) { e.printStackTrace(); } } }
- Explanation: This example creates a new file named example.txt (if it doesn’t exist) and writes the message “Hello, World!” into it. After writing, it closes the FileWriter to release resources.
2. Appending Data to an Existing File
By default, FileWriter overwrites the file.
However, you can append to an existing file by using the FileWriter constructor with true as the second parameter.
Example 2: Appending Text to a File
import java.io.FileWriter; import java.io.IOException; public class AppendFileWriterExample { public static void main(String[] args) { try { // Create a FileWriter in append mode FileWriter writer = new FileWriter("example.txt", true); // Append a message to the file writer.write("\nThis is an appended line."); // Close the FileWriter writer.close(); System.out.println("Successfully appended to the file."); } catch (IOException e) { e.printStackTrace(); } } }
- Explanation: Here, true in new FileWriter(“example.txt”, true) opens the file in append mode, so it adds new content instead of overwriting the file.
3. Writing Characters and Strings
You can write individual characters, arrays of characters, or entire strings to a file using FileWriter.
Example 3: Writing Individual Characters
import java.io.FileWriter; import java.io.IOException; public class WriteCharactersExample { public static void main(String[] args) { try { FileWriter writer = new FileWriter("characters.txt"); // Writing individual characters writer.write('H'); writer.write('e'); writer.write('l'); writer.write('l'); writer.write('o'); writer.close(); System.out.println("Successfully wrote characters to the file."); } catch (IOException e) { e.printStackTrace(); } } }
Example 4: Writing an Array of Characters
import java.io.FileWriter; import java.io.IOException; public class WriteCharArrayExample { public static void main(String[] args) { try { FileWriter writer = new FileWriter("charArray.txt"); // Write an array of characters char[] message = {'H', 'e', 'l', 'l', 'o', ' ', 'J', 'a', 'v', 'a'}; writer.write(message); writer.close(); System.out.println("Successfully wrote a character array to the file."); } catch (IOException e) { e.printStackTrace(); } } }
Example 5: Writing an Entire String
import java.io.FileWriter; import java.io.IOException; public class WriteStringExample { public static void main(String[] args) { try { FileWriter writer = new FileWriter("string.txt"); // Write a full string writer.write("This is a string being written to the file!"); writer.close(); System.out.println("Successfully wrote a string to the file."); } catch (IOException e) { e.printStackTrace(); } } }
4. Using BufferedWriter with FileWriter
For efficient writing, especially for large files, use BufferedWriter along with FileWriter.
BufferedWriter buffers the data, reducing the number of write operations to the disk.
Example 6: Using BufferedWriter for Buffered Writing
import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; public class BufferedWriterExample { public static void main(String[] args) { try { // Create FileWriter and BufferedWriter FileWriter writer = new FileWriter("buffered.txt"); BufferedWriter bufferedWriter = new BufferedWriter(writer); // Write multiple lines bufferedWriter.write("First line of text"); bufferedWriter.newLine(); // Add a new line bufferedWriter.write("Second line of text"); bufferedWriter.newLine(); bufferedWriter.write("Third line of text"); // Close the BufferedWriter and FileWriter bufferedWriter.close(); writer.close(); System.out.println("Successfully wrote to the file using BufferedWriter."); } catch (IOException e) { e.printStackTrace(); } } }
- Explanation: BufferedWriter buffers the output, minimizing I/O operations. Here, newLine() is used to add line breaks between lines.
5. Handling Exceptions and Closing FileWriter
Always close the FileWriter after writing to release system resources.
It’s recommended to use a try-with-resources statement to automatically close the FileWriter, which avoids potential memory leaks.
Example 7: Writing to a File with try-with-resources
import java.io.FileWriter; import java.io.IOException; public class TryWithResourcesExample { public static void main(String[] args) { // Use try-with-resources to auto-close FileWriter try (FileWriter writer = new FileWriter("resources.txt")) { writer.write("This file is written using try-with-resources."); System.out.println("Successfully wrote to the file with try-with-resources."); } catch (IOException e) { e.printStackTrace(); } } }
- Explanation: The try-with-resources statement automatically closes FileWriter at the end of the try block, eliminating the need for a separate close() call.
Summary of Key FileWriter Concepts
Feature | Description |
---|---|
Basic Writing | Creates a new file or overwrites existing content. |
Append Mode | Use new FileWriter(filename, true) to append instead of overwrite. |
Writing Characters | Write individual characters, character arrays, or strings. |
Buffered Writing | Use BufferedWriter to improve writing performance for large files. |
Auto-Close with try-with-resources | Ensures FileWriter is closed automatically, preventing memory leaks. |
Conclusion
In this tutorial, we explored various ways to use the FileWriter class in Java, including:
- Basic file writing operations.
- Appending content to an existing file.
- Writing individual characters, arrays, and entire strings.
- Buffered writing with BufferedWriter for enhanced performance.
- Exception handling and safe closure using try-with-resources.