java - 关于BufferedReader中readLine读取最后一行的问题
巴扎黑
巴扎黑 2017-04-17 14:59:34
[Java讨论组]

public static void main(String[] args) throws Exception{

    BufferedReader in = new BufferedReader(new FileReader("Test3.txt"));
    String line =null;
    while((line=in.readLine())!=null)
    {
        System.out.println(line);
    }
}

想问一下通过readLine方法读取一个文本行。通过下列字符之一即可认为某行已终止:换行 ('\n')、回车 ('\r') 或回车后直接跟着换行,但是在最后一行的时候并没有换行或者回车的字符啊,此时为什么会读取到最后一行呢?按理说最后一行是不应该被读取到的。求解!

巴扎黑
巴扎黑

全部回复(2)
天蓬老师

在BufferedReader中有一个private方法是用来判断是否到达Stream的结尾的,如下:

  • @return the number of chars read into the buffer, or -1 if the end of the source stream has been reached.

 private int fillBuf() throws IOException {

而在readLine()中有一段是这么写的:

 while (true) {
    pos = end;
    if (fillBuf() == -1) {
        // If there's no more input, return what we've read so far, if anything.
        return (result.length() > 0) ? result.toString() : null;
    }
    ...
PHP中文网

这个可以看下BufferedReader的源码,实际上还有一种情况,就是读到了文件结束位置(也就是最后一行),即使没有\n和\r也会返回这一行。

if (nextChar >= nChars) { /* EOF */
  if (s != null && s.length() > 0)
    return s.toString();
  else
    return null;
}
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号