Java按行读取文件文本内容

在工作和学习中,有时候会有一些场景,代码需要配合读取文件来执行,比如:读文件数据,来进行计算、组装SQL、更新操作...... 下面我们来讨论下,在Java中按行读取文件文件内容的方式有哪些?

一、前提说明

  • 读取的文件内容
    在这里插入图片描述
  • 测试代码
System.out.println("总行数:" + ids.size());
for (int i = 0; i < ids.size(); i++) {
	// System.out.println("第" + (i + 1) + "行内容:" + ids.get(i));
	String content = ids.get(i);
	System.out.println(String.format("第%d行内容:%s,内容长度:%d", i + 1, content, content.length()));
}
  • 输出结果
总行数:5
第1行内容:1,内容长度:1
第2行内容:2,内容长度:1
第3行内容:3,内容长度:1
第4行内容:4,内容长度:1
第5行内容:5,内容长度:1

二、方法

1、java.io.FileInputStream

File file = new File("G:\\ids.txt");
List<String> ids = new ArrayList<>();
try (FileInputStream fileInputStream = new FileInputStream(file);) {
	int size = fileInputStream.available();
	for (int i = 0; i < size; i++) {
		ids.add((char) fileInputStream.read() + "");
	}
} catch (IOException e) {
	e.printStackTrace();
}
总行数:13
第1行内容:1,内容长度:1
,内容长度:1
第3行内容:
,内容长度:1
第4行内容:2,内容长度:1
,内容长度:1
第6行内容:
,内容长度:1
第7行内容:3,内容长度:1
,内容长度:1
第9行内容:
,内容长度:1
第10行内容:4,内容长度:1
,内容长度:1
第12行内容:
,内容长度:1
第13行内容:5,内容长度:1

分析:虽然读取1个字符,但每行后面可能还有隐藏换行符`
总结:适用于按照字符一个个读取的场景

2、java.io.BufferedReader

FileReader就能用于读取文本文件,使用BufferedReader能提高读取文件的性能

File file = new File("G:\\ids.txt");
List<String> ids = new ArrayList<>();
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file));) {
	// Java8以后
	ids = bufferedReader.lines().collect(Collectors.toList());

	// Java7以前
	// String str = null;
	// while ((str = bufferedReader.readLine()) != null) {
	// 	ids.add(str);
	// }
} catch (IOException e) {
	e.printStackTrace();
}

3、java.nio.file.Files

三种写法都可以,直接就可以返回一个list

// java7以后
List<String> ids = Files.readAllLines(new File("G:\\ids.txt").toPath());
// java7以后
List<String> ids = Files.readAllLines(Paths.get("G:\\ids.txt"));
// java8以后
List<String> ids = Files.lines(Paths.get("G:\\ids.txt")).collect(Collectors.toList());

4、org.apache.commons.io.FileUtils

apache commons中的工具类

List<String> ids = FileUtils.readLines(new File("G:\\ids.txt"));

5、java.util.Scanner

Scanner类可以用来获取控制台的输入,也可以用来对文件的读取。之所以可以这样,是因为提供了构造函数重载

List<String> ids = new ArrayList<>();
try (Scanner sc = new Scanner(new File("G:\\ids.txt"))) {
    while (sc.hasNextLine()){
		ids.add(sc.nextLine());
	}
} catch (IOException e) {
    e.printStackTrace();
}
  • 13
    点赞
  • 43
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

程序员Forlan

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

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

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

打赏作者

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

抵扣说明:

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

余额充值