The Java FilterReader is employed for carrying out filtering tasks on a stream of readers. This serves as a foundational class for reading character streams that have been filtered.
FilterReader offers standard methods that forward all requests to the enclosed stream. Subclasses of FilterReader are expected to redefine certain methods and can introduce new methods and variables as needed.
Field
| Modifier | Type | Field | Description |
|---|---|---|---|
| protected | Reader | in | The underlying character-input stream. |
Constructors
| Modifier | Constructor | Description |
|---|---|---|
| protected | FilterReader(Reader in) | It creates a new filtered reader. |
Method
| 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 anarray. |
void |
reset() | It resets the stream. |
long |
skip(long n) | It skips characters. |
Example
In this instance, we will be working with a file named "javaFile123.txt" that includes the text "India is my country" within it. Our task involves replacing spaces with a question mark '?' in this file.
Example
import java.io.*;
class CustomFilterReader extends FilterReader {
CustomFilterReader(Reader in) {
super(in);
}
public int read() throws IOException {
int x = super.read();
if ((char) x == ' ')
return ((int) '?');
else
return x;
}
}
public class FilterReaderExample {
public static void main(String[] args) {
try {
Reader reader = new FileReader("javaFile123.txt");
CustomFilterReader fr = new CustomFilterReader(reader);
int i;
while ((i = fr.read()) != -1) {
System.out.print((char) i);
}
fr.close();
reader.close();
} catch (Exception e) {
e.getMessage();
}
}
}
Output:
Output
India?is?my?country