FilterWriter
What is Filtering?
A normal reader/writer class can read/write what we demand for. But lets say we have a special requirement of writing/reading. For Example: At the end of the file which we write, we want to print(write) Date. Which is a special requirement and this will be needed for each time we write a file. For this kind of scenario where by some very frequent and static processing is to be done each time then we can create our own FilterWriter which will do the job for us. So that manually we will not be doing it again and again. FilterWriter is an abstract class which does not have any abstract method. We can override the methods of it and perform our code instead. We are going to discuss another case here.
Aim
Write a program using FilterWriter which converts larges statements(having more than 15 chars) to a shorter statement and write a file.
e.g. If we tries to write “This is demo by Ankit”. It appends first 5 chars and last 5 chars of string with “…” and generate “This … Ankit” as a output.
import java.io.*; public class FilterDemo { public static void main(String[] args)throws Exception { File f = new File("data.txt"); FileWriter fw = new FileWriter(f); myFilterWriter mfw = new myFilterWriter(fw); mfw.write("This is demo by Ankit"); mfw.flush(); mfw.close(); } } class myFilterWriter extends FilterWriter { myFilterWriter(Writer w) { super(w); } @Override public void write(String str) throws IOException { int len = str.length(); String output = ""; if(len>15) { output = str.substring(0,5); output += "... "; output += str.substring(len-5,len); } super.write(output); } }
Recent Comments