1 package net.sf.logdistiller.util;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 import java.io.IOException;
18 import java.io.Reader;
19
20
21
22
23
24
25
26
27 public class BufferingReader
28 extends Reader
29 {
30 private int bufferBlockSize;
31
32 private char[] buffer;
33
34 private int begin = 0;
35
36 private int end = 0;
37
38 private final Reader reader;
39
40 public BufferingReader( Reader reader, int bufferBlockSize )
41 {
42 this.reader = reader;
43 this.bufferBlockSize = bufferBlockSize;
44 buffer = new char[bufferBlockSize];
45 }
46
47 public BufferingReader( Reader reader )
48 {
49 this( reader, 16384 );
50 }
51
52 public boolean ready()
53 throws IOException
54 {
55 return reader.ready();
56 }
57
58 public void close()
59 throws IOException
60 {
61 reader.close();
62 }
63
64 public int read( char[] cbuf, int off, int len )
65 throws IOException
66 {
67 int count = reader.read( cbuf, off, len );
68 if ( count > 0 )
69 {
70 if ( end + count >= buffer.length )
71 {
72 prepareBuffer( count + ( end - begin ) );
73 }
74 System.arraycopy( cbuf, off, buffer, end, count );
75 end += count;
76 }
77 return count;
78 }
79
80
81
82
83
84
85 public int getDataLength()
86 {
87 return ( end - begin );
88 }
89
90
91
92
93
94
95
96
97
98 public String freeData( int count )
99 {
100 if ( count > getDataLength() )
101 {
102 throw new IndexOutOfBoundsException( "asked for " + count + " chars, but buffer contains only "
103 + getDataLength() + " chars." );
104 }
105 String data = new String( buffer, begin, count );
106 begin += count;
107 return data;
108 }
109
110
111
112
113
114
115 public int getBufferSize()
116 {
117 return buffer.length;
118 }
119
120
121
122
123
124 public void shrinkBuffer()
125 {
126 int size = calculateBufferSize( end - begin );
127 if ( size < buffer.length )
128 {
129 char[] oldBuffer = buffer;
130 buffer = new char[size];
131 end -= begin;
132 System.arraycopy( oldBuffer, begin, buffer, 0, end );
133 begin = 0;
134 }
135 }
136
137
138
139
140
141
142
143 private void prepareBuffer( int size )
144 {
145 char[] oldBuffer = buffer;
146 if ( size > buffer.length )
147 {
148
149 buffer = new char[calculateBufferSize( size )];
150 }
151 end -= begin;
152 System.arraycopy( oldBuffer, begin, buffer, 0, end );
153 begin = 0;
154 }
155
156 private int calculateBufferSize( int size )
157 {
158 return bufferBlockSize * ( size / bufferBlockSize + 1 );
159 }
160 }