Java:如何读取文本文件 [英] Java: How to read a text file
问题描述
我想读取一个包含空格分隔值的文本文件.值为整数.如何读取它并将其放入数组列表中?
I want to read a text file containing space separated values. Values are integers. How can I read it and put it in an array list?
以下是文本文件内容的示例:
Here is an example of contents of the text file:
1 62 4 55 5 6 77
我想把它作为 [1, 62, 4, 55, 5, 6, 77]
放在一个数组列表中.我如何在 Java 中做到这一点?
I want to have it in an arraylist as [1, 62, 4, 55, 5, 6, 77]
. How can I do it in Java?
推荐答案
您可以使用 Files#readAllLines()
将文本文件的所有行放入List<字符串>
.
for (String line : Files.readAllLines(Paths.get("/path/to/file.txt"))) {
// ...
}
教程:基本 I/O > 文件 I/O > 阅读,编写和创建文本文件
您可以使用 String#split()
根据正则表达式将 String
分成几部分.
You can use String#split()
to split a String
in parts based on a regular expression.
for (String part : line.split("\s+")) {
// ...
}
您可以使用 Integer#valueOf()
将 String
转换为 Integer
.
You can use Integer#valueOf()
to convert a String
into an Integer
.
Integer i = Integer.valueOf(part);
您可以使用List#add()
将元素添加到 List
.
numbers.add(i);
教程:接口 > 列表接口
所以,简而言之(假设文件没有空行,也没有尾随/前导空格).
So, in a nutshell (assuming that the file doesn't have empty lines nor trailing/leading whitespace).
List<Integer> numbers = new ArrayList<>();
for (String line : Files.readAllLines(Paths.get("/path/to/file.txt"))) {
for (String part : line.split("\s+")) {
Integer i = Integer.valueOf(part);
numbers.add(i);
}
}
<小时>
如果您碰巧已经使用 Java 8,那么您甚至可以使用 Stream API,从 Files#lines()
.
List<Integer> numbers = Files.lines(Paths.get("/path/to/test.txt"))
.map(line -> line.split("\s+")).flatMap(Arrays::stream)
.map(Integer::valueOf)
.collect(Collectors.toList());
这篇关于Java:如何读取文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!