Java Writer Class

Java Writer Class

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

The Writer class of the java.io package is an abstract superclass that represents a stream of characters.

Since Writer is an abstract class, it is not useful by itself. However, its subclasses can be used to write data.


Subclasses of Writer

In order to use the functionality of the Writer, we can use its subclasses. Some of them are:

Subclasses of Java Writer are BufferedWriter, OutputStreamWriter, FileWriter and StringWriter.

We will learn about all these subclasses in the next tutorial.


Create a Writer

In order to create a Writer, we must import the java.io.Writer package first. Once we import the package, here is how we can create the writer.

// Creates a Writer
Writer output = new FileWriter();

Here, we have created a writer named output using the FileWriter class. It is because the Writer is an abstract class. Hence we cannot create an object of Writer.

Note: We can also create writers from other subclasses of the Writer class.


Methods of Writer

The Writer class provides different methods that are implemented by its subclasses. Here are some of the methods:

  • write(char[] array) - writes the characters from the specified array to the output stream
  • write(String data) - writes the specified string to the writer
  • append(char c) - inserts the specified character to the current writer
  • flush() - forces to write all the data present in the writer to the corresponding destination
  • close() - closes the writer

Example: Writer Using FileWriter

Here is how we can implement the Writer using the FileWriter class.

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

public class Main {

    public static void main(String args[]) {

        String data = "This is the data in the output file";

        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();
        }
    }
}

In the above example, we have created a writer using the FileWriter class. The writer is linked with the file output.txt.

Writer output = new FileWriter("output.txt");

To write data to the output.txt file, we have implemented these methods.

output.write();      // To write data to the file
output.close();      // To close the writer

When we run the program, the output.txt file is filled with the following content.

This is a line of text inside the file.

To learn more, visit Java Writer (official Java documentation).