import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
public class BufferedReaderDemo {
public static void main(String[] args) {
MyBufferedReader mbr = null;
try {
mbr = new MyBufferedReader(new FileReader("src/D.java"));
for (String line; (line = mbr.myReadLine()) != null;)
System.out.println(line);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (mbr != null) {
mbr.myClose();
mbr = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/*
* 自定义字符输入流缓冲区
*/
class MyBufferedReader {
//缓冲区中的字符流
private Reader r = null;
public MyBufferedReader(Reader r) {
this.r = r;
}
public String myReadLine() throws IOException {
//该方法缓冲数据的容器
StringBuilder sb = new StringBuilder();
/*
* 未读到回车换行就把读到的数据添加到
* 容器中,读到回车换行就把数据返回
*/
for (int ch; (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;
}
public void myClose() throws IOException {
r.close();
}
}