English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Arrays

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented Programming(III)

Java Exception Handling

Java List(List)

Java Queue(Queue)

Java Map Collections

Java Set Collections

Java Input Output(I/)

Java Reader/Writer

Other Java Topics

Java Writer Class

In this tutorial, we will learn about Java Writer, its subclasses, and their methods through an example.

The Writer class in the java.io package is an abstract superclass that represents character streams.

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

Writer Subclasses

To use the features of Writer, we can use its subclasses. Some of them are:

In the next tutorial, we will learn all these subclasses.

Create Writer

To create a Writer, we must first import the java.io.Writer package. After importing the package, we can create the writer.

//Create Writer
Writer output = new FileWriter();

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

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

Writer methods

The Writer class provides various methods implemented by its subclasses. Here are some methods:

  • write(char[] array) - Write the characters in the specified array to the output stream.

  • write(String data) - Write the specified string into the writer.

  • append(char c) - Insert the specified character into the current writer.

  • flush() - Force all data in the writer to be written to the corresponding destination.

  • close() - Close the writer

Example: Using FileWriter's Writer

This is how we use the FileWriter class to implement the method of Writer.

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 {
            //Create a Writer using FileWriter
            Writer output = new FileWriter("output.txt");
            //Write a string to the file
            output.write(data);
            //Close the writer
            output.close();
        }
        catch (Exception e) {
            e.getStackTrace();
        }
    }
}

In the above example, we used the FileWriter class to create the writer.writerWith the fileoutput.txtLink.

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

To write dataoutput.txtThe file, we have implemented these methods.

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

When we run the program,output.txtThe file will be filled with the following content.

This is a line of text inside the file.