Java - Custom Input/Output Streams

Introduction

In the following we will add a new reader class that is called LowerCaseReader.

It will read characters from a character-based stream and convert all characters to lowercase.

LowerCaseReader class is a concrete decorator class in the Reader class family.

It inherits from the FilterReader class.

LowerCaseReader needs to provide a constructor that will accept a Reader object.

class LowerCaseReader extends FilterReader {
       public LowerCaseReader(Reader in) {
                // Code for the constructor goes here
        }
        // More code goes here
}

Demo

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FilterReader;
import java.io.IOException;
import java.io.Reader;

public class Main {
  public static void main(String[] args) throws Exception {
    String fileName = "text.txt";
    LowerCaseReader lcr = new LowerCaseReader(new FileReader(fileName));
    int c = -1;//from w  w  w .  j  av  a  2  s. c o m
    while ((c = lcr.read()) != -1) {
      System.out.print((char) c);
    }
    lcr.close();

    BufferedReader br = new BufferedReader(new LowerCaseReader(new FileReader(
        fileName)));

    String str = null;
    while ((str = br.readLine()) != null) {
      System.out.println(str);
    }
    br.close();
  }
}

class LowerCaseReader extends FilterReader {
  public LowerCaseReader(Reader in) {
    super(in);
  }

  @Override
  public int read(char[] cbuf, int off, int len) throws IOException {
    int count = super.read(cbuf, off, len);
    if (count != -1) {
      // Convert all read characters to lowercase
      int limit = off + count;
      for (int i = off; i < limit; i++) {
        cbuf[i] = Character.toLowerCase(cbuf[i]);
      }
    }
    return count;
  }
}

Result