本帖最后由 周怡 于 2013-2-11 20:40 编辑
这个就是装饰模式嘛,你看下- public class BufferedWriter extends Writer {
- //装饰模式
- private Writer out;
- }
- //构造函数
- public BufferedWriter(Writer out, int sz) {
- super(out);
- if (sz <= 0)
- throw new IllegalArgumentException("Buffer size <= 0");
- this.out = out;
- cb = new char[sz];
- nChars = sz;
- nextChar = 0;
- //获取换行的符号\n \r,和方法System.getProperty("line.separator")一样
- lineSeparator = (String) java.security.AccessController.doPrivileged(
- new sun.security.action.GetPropertyAction("line.separator"));
- }
- //write有关
- public void write(int c) throws IOException {
- synchronized (lock) {
- //判断是否有输出流
- ensureOpen();
- //如果缓存数组写满了,就flush数组。
- if (nextChar >= nChars)
- flushBuffer();
- //将内容写入缓存数组中
- cb[nextChar++] = (char) c;
- }
- }
- //flush,这个方法就知道flush的重要性,
- void flushBuffer() throws IOException {
- synchronized (lock) {
- ensureOpen();
- if (nextChar == 0)
- return;
- //将数据写入流
- out.write(cb, 0, nextChar);
- nextChar = 0;
- }
- }
- public void write(String s, int off, int len) throws IOException {
- synchronized (lock) {
- ensureOpen();
-
- int b = off, t = off + len;
- while (b < t) {
- int d = min(nChars - nextChar, t - b);
- //将字符串转为字符数组
- s.getChars(b, b + d, cb, nextChar);
- //写入缓存数组
- b += d;
- nextChar += d;
- if (nextChar >= nChars)
- //如果写满了,就写入流中。
- flushBuffer();
- }
- }
- }
- //writeLine 写一个换行
- public void newLine() throws IOException {
- //同样写到缓存数组里
- write(lineSeparator);
- }
- //flush
- public void flush() throws IOException {
- synchronized (lock) {
- flushBuffer();
- out.flush();
- }
- }
- //关闭资源
- public void close() throws IOException {
- synchronized (lock) {
- if (out == null) {
- return;
- }
- try {
- //最后还释放了一次。不过没有执行flush方法,所以在close前还是要执行一次flush!
- flushBuffer();
- } finally {
- out.close();
- out = null;
- cb = null;
- }
- }
- }
复制代码 |