Java CharacterSetFilterReader-class And Method Code Example


Here is an example of how to use the CharacterSetFilterReader class from the Apache Commons IO library in Java:

import java.io.IOException;
import java.io.StringReader;
import org.apache.commons.io.input.CharacterSetFilterReader;

public class MyClass {
    public static void main(String[] args) throws IOException {
        StringReader input = new StringReader("This is an example text");
        CharacterSetFilterReader filteredReader = new CharacterSetFilterReader(input, "UTF-8");
        int nextChar = filteredReader.read();
        while (nextChar != -1) {
            System.out.print((char)nextChar);
            nextChar = filteredReader.read();
        }
    }
}

In this example, CharacterSetFilterReader is wrapping a StringReader that contains the string "This is an example text".

It allows a Reader to be wrapped in a filter that converts the character set of the input.

It reads in the input using the specified character set and returns the characters in the default character set.

The CharacterSetFilterReader is used in the same way as any other Reader, in this case it reads a character at a time until the end of the input is reached.

This will output:

This is an example text

Please note that this is a simple example and in real-world usage, you might want to do more complex processing on the characters before returning them.