Java-读取本地txt文件的问题

最近看到文件操作,偶然看到在读取的过程中略有不同,遂在这里简单的来解析下两种方法的不同之处:
其一:

这是在网上普遍看到的方法,来说下while中的条件,lineTxt为读取到的内容的承载对象字符串,bufferedReader.readLine()为整行读取内容,系统规定,当读取到流末尾后返回null,退出while循环。这里关闭文件是在读取结束后就执行的,博主认为不太妥当。

//效率高
 public void readTxtFile(String filePath) {
        try {
            File file = new File(filePath);
            if (file.isFile() && file.exists()) {
                InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "utf-8");
                BufferedReader br = new BufferedReader(isr);
                String lineTxt = null;
                while ((lineTxt = br.readLine()) != null) {
                    System.out.println(lineTxt);
                }
                br.close();
            } else {
                System.out.println("文件不存在!");
            }
        } catch (Exception e) {
            System.out.println("文件读取错误!");
        }

    }

其二:
此处while 循环中用字节数判断是否读取结束,fis.read(bytes)表示读取的字节数,文档中表明,当读取不到时返回-1,n为读取到的字节数(也可用字符来代替),还有就是关于try/catch的使用,最后的finally,关闭文件放在这里更合适点。

//效率低
        File fl = new File("image/1.txt");      
        System.out.println(fl.getAbsolutePath());
        // 因为file没有读写的能力,所以需要用InputStream
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(fl);
            // 定义一个字节数组,相当于缓存
            byte[] bytes = new byte[1024];
            int n = 0;// 得到实际读取到的字节数
            // 循环读取
            while ((n = fis.read(bytes)) != -1) {
                // 把字节转成string
                String s = new String(bytes, 0, n);
                System.out.println(s);
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            // 关闭文件,必须放这里
            try {
                fis.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

以上两种写法都可以拿到数据,博主对其中的一些认知有些不同,发出来大家看看,比较推荐第二种写法,原因上面已经给出,还请大家吧甄别。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CodingFire

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值