dsa

Java Writer

In this tutorial, we will learn about the Java Writer, its subclasses, its constructors and its methods with the help of an example.

Writer is an abstract class for writing to character streams. Since, it is an abstract class ,so we to use its derived classes or child classes for creating it's objects.

Child classes of Writer class

Constructors of Writer

Methods

MethodsDesciption
Writer append(char c)Appends the specified character to this writer.
Writer append(CharSequence csq)Appends the specified character sequence to this writer.
Writer append(CharSequence csq, int start, int end)Appends a subsequence of the specified character sequence to this writer.
abstract void close()Closes the stream, flushing it first.
abstract void flush()Flushes the stream.
void write(char[] cbuf)Writes an array of characters.
abstract void write(char[] cbuf, int off, int len)Writes a portion of an array of characters.
void write(int c)Writes a single character.
void write(String str)Writes a string.
void write(String str, int off, int len)Writes a portion of a string.

Examples :


import java.io.FileWriter;
import java.io.Writer;

public class Codemistic 
{

    	public static void main(String args[]) 
	{

	        String data = "This file consists of one line only.";

	        try 
		{
	            	// Creates a Writer using FileWriter
            		Writer output = new FileWriter("output.txt");

            		// Writes string to the file
            		output.write(data);

            		// Closes the writer
            		output.close();
        	}
        	catch (Exception e) 
		{
	    	        e.getStackTrace();
        	}
    	}
}


Output :

This will create a file named output.txt and the file will contain:
This file consists of one line only.