In this section we will discuss about the Writer class in Java.
In this section we will discuss about the Writer class in Java.In this section we will discuss about the Writer class in Java.
java.io.Writer is an abstract class which provides some methods to write characters to the stream. Object of this class can't be created directly. This class is a super class of all the classes which are involved in or to facilitate to write (output) the character streams. Classes descended from this class may overrides the methods of this class but the method write(char[], int, int), flush() and close() must be implemented by the subclasses.
Constructor Detail
Writer() | This is a default constructor which creates a writer for writing character
streams.
In such type of character streams writer synchronization of critical sections is
depend on the writer itself. Syntax : protected Writer() |
Writer(Object lock) | A parameterized constructor which creates a writer for writing character
streams. In such type of character streams writer synchronization of critical
sections is depend on the given object. Syntax : protected Writer(Object lock) |
Methods Detail
Example
To demonstrate how to use Writer to write into the output stream I am giving a simple example. In this example I have created a Java class named JavaWriterExample.java where I have created an object of Writer using BufferedWriter to write to the output stream and created object of FileWriter to write the stream to the file. Further in the example I have flushed and closed the stream using finally block.
Source Code
JavaWriterExample.java
import java.io.Writer; import java.io.FileWriter; import java.io.BufferedWriter; import java.io.IOException; public class JavaWriterExample { public static void main(String args[]) { char[] ch = {'a', 'b', 'c'}; FileWriter fw = null; Writer wr = null; //BufferedWriiter bw = null; try { fw = new FileWriter("test.txt"); wr = new BufferedWriter(fw); wr.write("Welcome to Roseindia"); wr.write(" "); wr.write(ch); System.out.println("\n File successfully written"); } catch(IOException ioe) { System.out.println(ioe); } finally { if(fw != null) { try { fw.flush(); wr.flush(); fw.close(); wr.close(); } catch(Exception e) { System.out.println(e); } } }//finally closed }// main closed }// class closed
Output
When you will compile and execute the above example like below then the output will be as follows :
When the output will show like the above then if you will open the directory what you have given the path at the time of creating of file (say test.txt) you will see that the file with the specified name is created and contains the text written by the Java program.
Source code of the above example can be downloaded from the link given below.
Ads