FilterReader
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: We want to read only those lines from the file which has “.” at the end. Rest we want to skip. 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 FilterReader which will do the job for us. So that manually we will not be doing it again and again. FilterReader 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 FilterReader which removes tags from the file content. e.g. <tag> should be removed.
import java.io.*; class NoTagReader extends FilterReader { boolean intag = false; public NoTagReader(Reader r) { super(r); } public int read(char[] buf, int from, int len) throws IOException { int numchars = 0; while (numchars == 0) { numchars = in.read(buf, from, len); if (numchars == -1) { return -1; } int last = from; for (int i = from; i < from + numchars; i++) { if (!intag) { if (buf[i] == '<') intag = true; else buf[last++] = buf[i]; } else if (buf[i] == '>') { intag = false; } } numchars = last - from; } return numchars; } public int read() throws IOException { char[] buf = new char[1]; int result = read(buf, 0, 1); if (result == -1) return -1; else return (int) buf[0]; } } class FilterReaderDemo { public static void main(String[] args) { try { NoTagReader ntr = new NoTagReader(new FileReader("data.txt")) BufferedReader in = new BufferedReader(ntr); String line; while ((line = in.readLine()) != null) { System.out.println(line); } in.close(); // Close the stream. } catch (Exception e) { System.err.println(e); } } }
Recent Comments