In java, the ‘writer’ class is an abstract class that defines character stream output. It is part of the ‘java.io’ package and is the superclass for all classes that write character streams.
Understanding Writer class in java with example
Key Features:
Abstract Class: Being abstract, ‘Writer’ cannot be instantiated directly. Instead, you use one of its subclasses.
Subclasses: Common subclasses include ‘BufferedWriter’, ‘FileWriter’, ‘PrintWriter’, ‘StringWriter’, and ‘OutputStreamWriter’.
Methods: Key methods provided by the ‘Writer’ class include.
‘write(int c)’: Writes a single character.
‘write(char[] cbuf, int off, int len)’: Writes a portion of an array of characters.
‘write(String str, int off, int len)’: Writes a portion of a string.
‘flush()’: Flushes the stream.
‘close()’: Closes the stream, releasing any resources associated with it.
Example:
import java.io.FileWriter; import java.io.IOException; public class WriterExample { public static void main(String[] args) { try { // Create a FileWriter object for "output.txt" FileWriter writer = new FileWriter("output.txt"); // Write a message to the file writer.write("Hello, world!"); // Close the writer writer.close(); System.out.println("Data has been written to the file."); } catch (IOException e) { System.err.println("An error occurred: " + e.getMessage()); } } }
In this Example:
We create a ‘FileWriter’ object to write to the file named “output.txt”. Then, we use the ‘write’ method of the ‘FileWriter’ object to write the message “Hello, World!” to the file. Finally, we close the ‘FileWriter’ object.
Output: Data has been written to the file. In output.txt file Hello, World!
Common Use Cases
Writing to Files: Using ‘FileWriter’ or ‘BufferedWriter’ for efficient file writing.
Formatted Output: Using ‘PrintWriter’ for printing formatted text.
In-Memory String Construction: Using ‘StringWriter’ for manipulating string in memory.
OutputStream Conversion: Using ‘OutputStreamWriter’ to write character data to byte streams.