![]() |
VOOZH | about |
The Java writer class is an abstract class in the java.io package. It is designed for writing character streams. It provides methods for writing characters, arrays of characters and strings to files, memory, or other output destinations.
public abstract class Writer implements Appendable, Closeable, Flushable
Since itβs an abstract class, we canβt instantiate it directly; instead, we use concrete subclasses like FileWriter, BufferedWriter or PrintWriter.
Message written
Explanation: Creates a FileWriter object to write "Hello, World!" into example.txt. After writing, it closes the stream to ensure data is saved and resources are released.
The Writer class in Java has two protected constructors that allow for the creation of character streams with synchronization capabilities.
Example 1: Writing Characters to a File
Data written successfully.
Output File: example.txt
Explanation: Creates a FileWriter instance to write text data to example.txt. Writes the message "Hello, Java Writer Class!" and closes the writer to finish safely.
Example 2: Using BufferedWriter for Efficiency
Data written using BufferedWriter.
Output File: buffered.txt
Explanation: Uses BufferedWriter to improve performance by temporarily storing data before writing it. Writes two lines of text into buffered.txt and automatically closes the stream using try-with-resources.
Example 3: Appending Data to a File
Data appended successfully.
Output File: example.txt
Explanation: Opens the existing file example.txt in append mode by passing true to FileWriter. Adds a new line "This line was appended later." without overwriting the previous data.
There are certain methods associated with the Java Writer class as mentioned below:
| Method | Description |
|---|---|
| write(int char) | Writes a single character to the character stream. |
| write(String str) | Writes an entire string to the character stream. |
| write(String str, int offset, int maxlen) | Writes a specific portion of the string to the character stream, starting at offset and writing maxlen characters. |
| write(char[] carray) | Writes the entire character array to the character stream. |
| write(char[] carray, int offset, int maxlen) | Writes a specific portion of the character array to the character stream, starting at offset and writing maxlen characters. |
| close() | Closes the character stream after flushing it. |
| flush() | Flushes the Writer stream; ensures that any buffered data is written to the underlying output. |
| append(char c) | Appends a single character to the Writer. |
| append(CharSequence char_sq) | Appends the specified character sequence to the Writer. |
| append(CharSequence char_sq, int start, int end) | Appends a specific subsequence of the given character sequence to the Writer. |