1 7 8 package java.io; 9 10 11 47 48 public class BufferedWriter extends Writer { 49 50 private Writer out; 51 52 private char cb[]; 53 private int nChars, nextChar; 54 55 private static int defaultCharBufferSize = 8192; 56 57 61 private String lineSeparator; 62 63 69 public BufferedWriter(Writer out) { 70 this(out, defaultCharBufferSize); 71 } 72 73 82 public BufferedWriter(Writer out, int sz) { 83 super(out); 84 if (sz <= 0) 85 throw new IllegalArgumentException ("Buffer size <= 0"); 86 this.out = out; 87 cb = new char[sz]; 88 nChars = sz; 89 nextChar = 0; 90 91 lineSeparator = (String ) java.security.AccessController.doPrivileged( 92 new sun.security.action.GetPropertyAction("line.separator")); 93 } 94 95 96 private void ensureOpen() throws IOException { 97 if (out == null) 98 throw new IOException ("Stream closed"); 99 } 100 101 106 void flushBuffer() throws IOException { 107 synchronized (lock) { 108 ensureOpen(); 109 if (nextChar == 0) 110 return; 111 out.write(cb, 0, nextChar); 112 nextChar = 0; 113 } 114 } 115 116 121 public void write(int c) throws IOException { 122 synchronized (lock) { 123 ensureOpen(); 124 if (nextChar >= nChars) 125 flushBuffer(); 126 cb[nextChar++] = (char) c; 127 } 128 } 129 130 134 private int min(int a, int b) { 135 if (a < b) return a; 136 return b; 137 } 138 139 155 public void write(char cbuf[], int off, int len) throws IOException { 156 synchronized (lock) { 157 ensureOpen(); 158 if ((off < 0) || (off > cbuf.length) || (len < 0) || 159 ((off + len) > cbuf.length) || ((off + len) < 0)) { 160 throw new IndexOutOfBoundsException (); 161 } else if (len == 0) { 162 return; 163 } 164 165 if (len >= nChars) { 166 169 flushBuffer(); 170 out.write(cbuf, off, len); 171 return; 172 } 173 174 int b = off, t = off + len; 175 while (b < t) { 176 int d = min(nChars - nextChar, t - b); 177 System.arraycopy(cbuf, b, cb, nextChar, d); 178 b += d; 179 nextChar += d; 180 if (nextChar >= nChars) 181 flushBuffer(); 182 } 183 } 184 } 185 186 201 public void write(String s, int off, int len) throws IOException { 202 synchronized (lock) { 203 ensureOpen(); 204 205 int b = off, t = off + len; 206 while (b < t) { 207 int d = min(nChars - nextChar, t - b); 208 s.getChars(b, b + d, cb, nextChar); 209 b += d; 210 nextChar += d; 211 if (nextChar >= nChars) 212 flushBuffer(); 213 } 214 } 215 } 216 217 224 public void newLine() throws IOException { 225 write(lineSeparator); 226 } 227 228 233 public void flush() throws IOException { 234 synchronized (lock) { 235 flushBuffer(); 236 out.flush(); 237 } 238 } 239 240 245 public void close() throws IOException { 246 synchronized (lock) { 247 if (out == null) 248 return; 249 flushBuffer(); 250 out.close(); 251 out = null; 252 cb = null; 253 } 254 } 255 256 } 257 | Popular Tags |