Java FilterReader class is an abstract class used to read filtered character streams.
In this chapter, we will learn what the FilterReader class is, why it is used, its declaration, constructors, methods, and examples to understand how filtering works on character input streams.
The FilterReader class is a character input stream that wraps another Reader and filters the data read from it.
It provides default implementations that simply pass all read requests to the underlying reader. Subclasses of FilterReader override one or more methods to modify or filter the data before it is returned to the caller.
FilterReader is mainly used when we want to transform, validate, or modify character data while reading it from an input source such as a file or string.
The FilterReader class is a part of the java.io package and extends the Reader class.
The field of FilterReader class is as follows:
| Modifier | Type | Field | Description |
|---|---|---|---|
| protected | Reader | in | The underlying character-input stream. |
The FilterReader class provides a protected constructor that is used by its subclasses.
This constructor creates a new filtered reader that wraps the specified reader.
Syntax:
Here is the syntax:
The following example demonstrates how a FilterReader subclass is created using the constructor.
The FilterReader class provides the following methods to read and manage character streams.
| Modifier and Type | Method | Description |
|---|---|---|
| void | close() | It closes the stream and releases any system resources associated with it. |
| void | mark(int readAheadLimit) | It marks the present position in the stream. |
| boolean | markSupported() | It tells whether this stream supports the mark() operation. |
| boolean | ready() | It tells whether this stream is ready to be read. |
| int | read() | It reads a single character. |
| int | read(char[] cbuf, int off, int len) | It reads characters into a portion of an array. |
| void | reset() | It resets the stream. |
| long | skip(long n) | It skips characters. |
Practice the following examples to understand how the FilterReader class works in real scenarios.
The following example demonstrates how a custom FilterReader replaces spaces with a question mark (?) while reading data from a file.
File Content (javaFile123.txt):
India is my country
Output:
India?is?my?country
The following example demonstrates how a custom FilterReader converts all characters to uppercase while reading data from a file.
File Content (input.txt):
Java FilterReader Example
Output:
JAVA FILTERREADER EXAMPLE
We request you to subscribe our newsletter for upcoming updates.