java读取字母数字文本文件并尝试存储到列表或数组
我使用scanner.usedelimiter("[^0-9|,]")
这个模式来避免文本文件中的字母。然后使用hasNext和next()方法存储到字符串,然后使用list,但list添加了额外的o和空格
我使用Scanner类读取一个文本文件,并从该文本文件中仅提取数字
Scanner sc = new Scanner("123.txt");
sc.useDelimiter("[^0-9|,|-]");
while (sc.hasNext()) {
String s = null;
s = sc.next();
list.add(s.replaceAll("\\s+",""));
}
实际文件包含数据
Class Student Details
1 total 25 students with 80% pass
2A - 3B total 90 students with 70% pass
4A - 5B total 69 students with 80% pass 10 distinction
预期产量
1 25 80
2 3 90 70
4 5 69 80 10
# 1 楼答案
另一种解决方案:不使用Scanner,您可以导入
java.nio
包,尤其是Files
类:获得文件中所有行的列表后,可以对它们进行迭代,并用空格替换每个非数字:
# 2 楼答案
您可以将以下代码库与Java8特性结合使用
# 3 楼答案
使用这样的
123.txt
文件:您可以使用正则表达式拆分每一行,只获取数字:
输出: