BufferedReader类中特有方法readLine原理:
无论是读一行,还是获取多个字符,其实最终都是在硬盘上一个一个读取,所以最终使用的还是read方法一次读一个的方法。
下面自定义一个类中包含一个和readLine一致的方法功能来模拟一下BufferedReader。
读取buf.txt这个文件:
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsISM3YDNzIDN3EzNyUDM1EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
代码如下:
class MyBufReader{
private FileReader r;
MyBufReader(FileReader r)
{
this.r=r;
}
//可以一次读一行的方法
public String myreadLine() throws IOException
{
//定义一个临时容器;原BufferReader封装的是字符数组
//为了演示方便,定义一个StringBuilder容器,因为最终还是要将数据转换成字符串
StringBuilder sb=new StringBuilder();
int ch=;
while((ch=r.read())!=-)
{
if(ch=='\r')
continue;
if(ch=='\n')
return sb.toString();
else
sb.append((char)ch);
}
if((sb.length())!=)
return sb.toString();
return null;
}
public void myClose() throws IOException
{
r.close();
}
}
public class MyBufReaderDemo {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
FileReader fr=new FileReader("buf.txt");
MyBufReader mybuf=new MyBufReader(fr);
String line=null;
while((line=mybuf.myreadLine())!=null)
{
System.out.println(line);
}
mybuf.myClose();
}
}
代码中 myreadLine()方法中的while循环中有如下代码:
if((sb.length())!=)
return sb.toString();
如果没有此代码行,txt文件最后一行没有回车键时,程序运行读取结果如下:
总之,楼主最近学习总结发现:要想写出一个好程序,首先应该将程序各种可能出现的情况考虑周全,想好测试用例…这样用户使用时才会流畅,我们所写出的程序才能发挥出它最大的价值!!!!