使用BufferedReader循环读文件(新手要注意的细节)

使用BufferedReader(缓存读取流)可以每次读取文件的一行。对于文件内容如果是按行为单位排列的话,则使用BufferedReader来读取文件还是比较方便的。

举例如下

1、BufferedReader读取一行

在F盘下有个txt文件,文件内容为
在这里插入图片描述

import java.io.*;

public class test {
    public static void main(String[] args)  {
	BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader("F:\\test.txt"));
            System.out.println(br.readLine());
        } catch (IOException e) {
            e.printStackTrace();
        }
}

结果为:

哈哈0
2、BufferedReader循环读每一行
import java.io.*;

public class test {
    public static void main(String[] args)  {
	BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader("F:\\test.txt"));
            String text = null;
            //读取内容为null则表示读到了文件末尾
        	while ((text = br.readLine()) != null) {
            System.out.println(text);
       		 }
        } catch (IOException e) {
            e.printStackTrace();
        }
}

结果为:

哈哈0
哈哈1
哈哈2
哈哈3
哈哈4
哈哈5
哈哈6
哈哈7
哈哈8
哈哈9
3、注意细节

新手如果没不注意,容易写成:

import java.io.*;

public class test {
    public static void main(String[] args)  {
	BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader("F:\\test.txt"));
            String text = null;
            //
        	while (true) {
	            if (br.readLine() == null) {
	                break;
	            }
            System.out.println(br.readLine());
       		 }
        } catch (IOException e) {
            e.printStackTrace();
        }
}

结果为:

哈哈1
哈哈3
哈哈5
哈哈7
哈哈9

原因

while (true) {
    if (br.readLine() == null) {
        break;
    }
   System.out.println(br.readLine());
 }

因为在while循环中, if 语句在做判断时,其实已经读取了一行,而读取的这行没有被打印出来,所以就造成了只打印了一部分。

  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值