Java FilterWriter class is an abstract class that is used to write filtered character streams.
In this chapter, we will learn what the FilterWriter class is, why it is used, its declaration, fields, constructors, methods, and examples to understand how it works in Java I/O.
The FilterWriter class is an abstract character output stream that wraps another Writer object to provide filtered or modified output.
It is mainly used as a base class for creating custom writer classes. Subclasses of FilterWriter override one or more writing methods to modify the data before writing it to the underlying writer. Classes like BufferedWriter internally use this concept to add extra functionality.
The FilterWriter class is a part of the java.io package and extends the Writer class.
The FilterWriter class provides a protected constructor that is used by its subclasses.
This constructor creates a FilterWriter object that wraps the specified Writer.
Syntax:
Here is the syntax:
Note:Since FilterWriter is an abstract class, it cannot be instantiated directly. This constructor is used inside subclasses.
The following example demonstrates how a custom class extends FilterWriter and uses its constructor.
The FilterWriter class provides the following commonly used methods:
| Modifier and Type | Method | Description |
|---|---|---|
| void | close() | It closes the stream, flushing it first. |
| void | flush() | It flushes the stream. |
| void | write(char[] cbuf, int off, int len) | It writes a portion of an array of characters. |
| void | write(int c) | It writes a single character. |
| void | write(String str, int off, int len) | It writes a portion of a string. |
Practice the following examples to understand the concept and usage of the FilterWriter class.
The following example demonstrates how to create a custom FilterWriter that converts text to lowercase before writing it to a file.
Output:
i love my country
While running the current program if the current working directory does not contain the file, a new file is created and CustomFileWriter will write the text "I LOVE MY COUNTRY" in lowercase to the file.
The following example demonstrates how a custom FilterWriter modifies data before writing it to a file.
Here, the custom writer converts all characters to lowercase before storing them in the file.
Output:
java filterwriter second example
We request you to subscribe our newsletter for upcoming updates.