/* * 模拟字符缓冲读入流:BufferedReader * * 分析: * 1.要属于流的体系 * 2.要有一个Reader类型的成员变量 * 3.要有一个带参数的构造方法接收外部传入的流对象 * 4.模拟readLine(),实现读一行的功能 * 5.关闭流 */ import java.io.FileReader; import java.io.IOException; import java.io.Reader; //1.要属于流的体系 class MyBufferedReader extends Reader{ //2.要有一个Reader类型的成员变量 Reader reader; //3.要有一个带参数的构造方法接收外部传入的流对象 public MyBufferedReader(Reader reader) { this.reader = reader; } //4.模拟readLine(),实现读一行的功能 public String readLine() throws IOException { //a.创建一个临时的可变字符串,用于装当前行的字符 StringBuffer stringBuffer = new StringBuffer(); //b.使用read()方法读 int num = 0; while ((num = this.reader.read()) != -1) { if (num == '\r') { continue; }else if (num == '\n') { return stringBuffer.toString(); }else { stringBuffer.append((char)num); } } //当文本为空时 if (stringBuffer.length() == 0) { return null; } //当文本只有一行,没有换行符 return stringBuffer.toString(); //增加效率的代码 } //5.关闭流 public void close() throws IOException { //关闭自己 this.reader.close(); } @Override public int read(char[] cbuf, int off, int len) throws IOException { // TODO Auto-generated method stub return 0; } } public class Demo11 { public static void main(String[] args) throws IOException { MyBufferedReader myBufferedReader = new MyBufferedReader(new FileReader("text3.txt")); String data = null; while ((data = myBufferedReader.readLine()) != null) { System.out.print(data); System.out.println(); } myBufferedReader.close(); } }