- import java.io.*;
- class MyBufferedReader extends Reader
- {
- private Reader r;
- MyBufferedReader(Reader r)
- {
- this.r = r;
- }
- //可以一次读一行数据的方法
- public String MyReaderLine()throws IOException
- {
- //定义一个临时容器,原BufferReader封装的是字符数组
- //为了演示方便,定义一个StringBuilder容器,因为最终
- //还是要将数据变成字符串
- StringBuilder sb = new StringBuilder();
- int ch = 0;
- while((ch=r.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;
-
- }
- /*
- 覆盖Reader类中的抽象方法
- */
- public void close()throws IOException
- {
- r.close();
- }
-
- public int read(char[] cbuf,int off,int len)throws IOException
- {
- return r.read(cbuf,off,len);
- }
- public void myClose()throws IOException
- {
- r.close();
- }
- }
- class MyBufferedReaderDemo
- {
- public static void main(String[] args)throws IOException
- {
- FileReader fr = new FileReader("Demo.txt");
- MyBufferedReader myBuf = new MyBufferedReader(fr);
- String line = null;
- while((line=myBuf.MyReaderLine())!=null)
- {
- System.out.println(line);
- }
- myBuf.myClose();
- }
- }
复制代码
自定义装饰类为什么要覆盖Reader类中的抽象方法? |