KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > roblisa > classfinder > FilteredInputStream


1 /**
2  * ClassFinder - a javadoc webserver.
3  * Copyright (C) 2003 Rob Nielsen
4  * rob@roblisa.com
5  * http://www.roblisa.com/java/classfinder/
6  *
7  * Released under the GNU GPL - http://www.gnu.org/copyleft/gpl.html
8  */

9 package com.roblisa.classfinder;
10
11 import java.io.*;
12
13 public class FilteredInputStream extends InputStream
14 {
15     int[] buf=new int[100];
16     int read=0;
17     int write=0;
18     int available=0;
19     boolean finished=false;
20     InputStream is;
21
22     public FilteredInputStream(InputStream is)
23     {
24         this.is=is;
25     }
26
27     public void filter(int b)
28     {
29         write(b);
30     }
31
32     public void write(int b)
33     {
34         if (b!=-1)
35         {
36             if (available==buf.length)
37             {
38                 int[] temp=new int[buf.length*2];
39
40                 int len=Math.min(available,buf.length-read);
41
42                 System.arraycopy(buf,read,temp,0,len);
43                 if (len<available)
44                     System.arraycopy(buf,0,temp,len,available-len);
45
46                 buf=temp;
47                 read=0;
48                 write=available;
49             }
50             buf[write]=b;
51             write=(write+1)%buf.length;
52             available++;
53         }
54     }
55
56     public void write(String s)
57     {
58         byte[] b=s.getBytes();
59         for(int i=0;i<b.length;i++)
60             write(b[i]);
61     }
62
63     public int read() throws IOException
64     {
65         while(available>0||!finished)
66         {
67             if (available>0)
68             {
69                 int r=buf[read];
70                 read=(read+1)%buf.length;
71                 available--;
72                 return r;
73             }
74             else
75             if (!finished)
76             {
77                 int r=is.read();
78                 filter(r);
79                 finished=(r==-1);
80                 continue;
81             }
82             else
83                 break;
84         }
85         return -1;
86     }
87
88     public void close() throws IOException
89     {
90         is.close();
91     }
92 }
Popular Tags