f3aedd61d337ef1e0d7693b40b65c29253855f78
[mir.git] / source / mir / misc / LineFilterWriter.java
1 package mir.misc;
2 import java.io.*;
3
4 /**
5  *  LineFilterWriter eliminates superfluous \t \r \n and spaces
6  *  and thus compresses the output of html
7  *
8  **/
9 public final class LineFilterWriter extends PrintWriter{
10
11   protected Writer out;
12
13   public LineFilterWriter(Writer out) {
14     super(out);
15     this.out=out;
16   }
17
18   public final void write(String str){
19     int i,j,len;
20     boolean state=true;
21     char c;
22     len=str.length();
23     if (len==1) {try{out.write(str);}catch(IOException e){}return;}
24     StringBuffer sbuf = new StringBuffer();
25
26     for(i=0;i<len;i++) {
27       c=str.charAt(i);
28       if(state) {
29         j = str.indexOf('\n',i);
30         if (j==-1) j=len-1;
31                                 sbuf.append(str.substring(i,j+1));
32         i=j;
33         state=false;
34       }
35       else
36          if (!Character.isWhitespace(c)) {
37                                                 sbuf.append(c);
38             state=true;
39          }
40     }
41     try{out.write(sbuf.toString());}catch(IOException e){;}
42   }
43
44   public final void write(char[] cbuf, int off,int len){
45     int i,j=off;
46     boolean state=true;
47     char c;
48
49     for(i=off;i<len;i++) {
50       c=cbuf[i];
51       if(state) {
52         if (c=='\n') state=false;
53         cbuf[j++]=c;
54       }
55       else
56          if (!Character.isWhitespace(c)) {
57                                                 cbuf[j++]=c;
58             state=true;
59          }
60     }
61     try{out.write(cbuf,off,j);}catch(IOException e){;}
62   }
63
64
65 }