Creating an OutputStream that manipulates the data written to it

Create a class that extends from FilterOutputStream and override the method write in which you convert the original value to a new value.

Following example introduces the ChangeCaseOutputStream which will convert any character to uppercase or lowercase depending on how you instantiated the class.

Main.java:

import java.io.*;
 
public class Main {
   public static void main(String args[]) {
      try {
         FileOutputStream fos = new FileOutputStream("test.out");
         ChangeCaseOutputStream ccos = new ChangeCaseOutputStream(
                                        ChangeCaseOutputStream.UPPERCASE, fos);
         ccos.write("hello, world!".getBytes());
         ccos.flush();
         ccos.close();
      }
      catch(FileNotFoundException e) {
         System.out.println(e);
      }
      catch(IOException e) {
         System.out.println(e);
      }
   }
}
 
class ChangeCaseOutputStream extends FilterOutputStream {
   public static final int LOWERCASE = 1;
   public static final int UPPERCASE = 2;
 
   private int conversionType;
 
   public ChangeCaseOutputStream(int conversionType, OutputStream in) {
      super(in);
 
      this.conversionType = conversionType;
   }
 
   public void write(int b) throws IOException {
      if (conversionType == LOWERCASE) {
         out.write((int) Character.toLowerCase((char) b));
      }
      else if (conversionType == UPPERCASE) {
         out.write((int) Character.toUpperCase((char) b));
      }
   }
}