这个原理在毕老师的课程中有讲过,我把源码附上,源码中有注释,您看一下就应该明白了
- import java.io.FileReader;
- import java.io.IOException;
- /*
- * BufferedReader读取流对象缓冲区中readLine()的原理实现
- * readLine()底层用的其实还是read,而关闭缓冲区底层用的其实是关闭流对象
- * readLine(),将换行符和回车符以外的字符返回到缓冲区,满一行则返回本行字符
- * 如果判断满一行:
- * windows中换行:\r\n
- * Linux中换行:\n
- * 为了实现跨平台,若碰到\r的时候,继续读取下一个字符,若\n则返回字符串
- */
- public class ReadLineMethodPrinciple {
- public static void main(String[] args)
- {
- // TODO Auto-generated method stub
- MyBufferedReader mbuf = null;
- try
- {
- mbuf = new MyBufferedReader(new FileReader("DateTest.java"));
- String line = "";
- while((line=mbuf.myReadLine())!=null)
- {
- sop(line);
- }
- }
- catch(IOException e)
- {
- throw new RuntimeException("文件读取失败");
- }
- finally
- {
- try
- {
- if(mbuf!=null)
- mbuf.myClose();
- }
- catch (IOException e)
- {
- throw new RuntimeException("文件关闭失败");
- }
- }
-
-
-
- }
- public static void sop(Object obj)
- {
- System.out.println(obj);
- }
- }
- class MyBufferedReader
- {
- private FileReader r = null;
- MyBufferedReader(FileReader r)
- {
- this.r = r;
- }
- public String myReadLine() throws IOException
- {
- StringBuilder sb = new StringBuilder();
- int ch = 0;
- while((ch=r.read())!=-1)
- {
- if(ch=='\r')
- continue;
- if(ch=='\n') //遇到\n返回字符串
- return sb.toString();
- sb.append((char)ch); //将字符存入字符串缓冲区
- }
- if(sb.length()!=0) //这个判断是为了最后一行没有换行标记的情况下返回本行字符
- return sb.toString();
- return null;
- }
- public void myClose() throws IOException
- {
- r.close();
- }
- }
复制代码 |