1. 程式人生 > >字符流緩沖區原理之裝飾模式

字符流緩沖區原理之裝飾模式

turn dem append ngs except new public lin ktr

import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;

/**

  • 模擬字符流緩沖區 readline()
  • 裝飾模式
  • @author WangShuang
  • */
    public class Demo {

    public static void main(String[] args) {
    MyBufferedReader my = null;
    try {
    FileReader fr = new FileReader("c:\字符流緩沖區.txt");
    my = new MyBufferedReader(fr);

    String buff = null;
    while((buff = my.myReadLine())!=null){
    System.out.println(buff);
    }
    } catch (Exception e) {
    throw new RuntimeException("讀取錯誤");
    }finally {
    try {
    if(my!=null)
    my.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }

    }
    }
    class MyBufferedReader extends Reader {
    Reader in = null;
    public MyBufferedReader(Reader in) {

    this.in = in;
    }
    //增強的方法
    public String myReadLine() throws IOException{
    StringBuffer sb = new StringBuffer();
    int ch = 0;
    while((ch = in.read())!=-1){
    if(ch == ‘\r‘)
    continue;
    if(ch== ‘\n‘)
    return sb.toString();
    else
    sb.append((char)ch);
    }
    if(sb.length()!=0){
    return sb.toString();
    }
    return null;}
    @Override
    br/>}
    @Override
    return in.read(cbuf, off, len);}
    @Override
    br/>}
    @Override
    in.close();

    }

}

字符流緩沖區原理之裝飾模式