In this tutorial , We will learn about writer Class in java. Writer is an abstract class that defines streaming character output. All of the methods in this class return a void value and throw an IOException in the case of errors.
- The ‘Writer’ class provides a common set of methods for writing character data to different output destinations,such as files, network connection, or in-memory buffers.
- It follows a character oriented approach, allowing you to write characters,strings, and character arrays.
Subclasses of writer
In order to use the functionality of the writer, we can use its subclasses. Some of them are:
- BufferedWriter : This class wrap around another writer and adds buffering functionality,which can improve the performance when writing large amounts of data.
- OutputStreamWriter : This class is a bridge between character streams and byte streams. It converts character data into byte data using a specified character encoding.
- FileWriter : This class is used to write character data to a file. It extends the ‘Writer’ class and provides methods specifically for writring to files.
- PrintWriter : This class provides methods for writing formatted representations of objects to a text output stream.
Methods of Writer
The writer class provides different methods that are implemented by its subclasses. Here are some commonly used methods:
- Write(int c) : This method writes a single character to the output stream. It takes an integer value as the parameter,which represents the unicode value of the character to be written.
- Write(char[] cbuf) : This method writes an array of characters to the output stream.It takes a character as the parameter .
- Write(String str) : This method writes a string to the output stream . It takes string as the parameter.
- flush() : This method flushes the output stream, ensuring that any buffered data is written immediately.
- close() : This method closes the output stream. It not only flushes any buffered data but also releases any system resources asociated with the stream.
Example for Writer class in java
import java.io.FileWriter; import java.io.IOException; public class WriterClassEmp { public static void main(String[] args) { try { FileWriter writer = new FileWriter("demo.txt"); writer.write("Hello, World!"); writer.close(); System.out.println("Data written into file successfully"); } catch(IOException e) { System.out.println("An error occurred while writing to file"); e.printStackTrace(); } } }
Output : An error occurred while writing to file
In the above example, we create a “FileWriter” object named “writer” and specify the files name as “demo.txt”.We then use the “write()” method to write the text “Hello, World!” to the file.
Finally,we close the “FileWriter” using the “close()” method to ensure that all the data is flushed and the file is closed.