[英]Java | Finding specific lines from file
所以我目前正在研究学校的一个项目。 我以这种格式将客户的数据保存在 .txt 文件中
-----
17-03-2020 15:49
WashType: De Luxe
ID: 1, Name: Janus Pedersen
-----
-----
20-03-2020 13:07
WashType: Standard
ID: 2, Name: Hardy Akira
-----
为了感谢客户使用此服务,我想在每购买 10 次后给客户一些电影票。 为此,我想再次阅读此文件并查找他们的 ID 并进行计数,但我根本无法完成这项工作。 我最初的想法是这样的,但它一直给我一个空指针
String[] words;
FileReader fr = new FileReader("stats.txt");
BufferedReader br = new BufferedReader(fr);
String s;
String input = String.valueOf(washCard.getCardID());
int count=0;
while((s=br.readLine())!=null)
{
words=s.split(" ");
for (String word : words)
{
if (word.equals(input))
{
count++;
System.out.println(word);
}
}
}
有人对此有什么好主意吗? 为了让事情更容易,我已将其全部添加到 github 存储库中: https : //github.com/rasm937k/curly-broccoli
您可以为此使用 Java 8 流:
Files.lines(Paths.get("stats.txt"))
.map(line -> line.split(" "))
.filter(words -> words[5].equals(washCardId))
.count();
这里还有一个关于 Java 8 Streams 的不错的教程: https : //www.baeldung.com/java-8-streams
以下代码基于Michał Kaciuba 的回答,但经过调整以适合您的stats.txt
文件的实际格式。 我不知道如何将其作为评论发布,因此我将其发布为答案,但正如我所说,Michał Kaciuba 应该受到赞扬,我认为您应该接受他的回答。 请注意,代码的解释遵循实际代码。
String input = String.valueOf(washCard.getCardID());
Pattern pttrn = Pattern.compile("^ID: (\\d+)");
Path p = Paths.get("stats.txt");
try {
long count = Files.lines(p) //throws java.io.IOException
.filter(l -> {Matcher mtchr = pttrn.matcher(l); return mtchr.find() && input.equals(mtchr.group(1));})
.count();
System.out.println(count);
}
catch (IOException x) {
x.printStackTrace();
}
Files.lines(p)
创建一个流,其中流中的每个元素都是来自文件stats.txt
,即一个String
。
正则表达式匹配以ID:
开头的行ID:
后跟一个空格,后跟一系列一个或多个数字。 数字部分被称为捕获组,因为它被括在括号中。
filter()
检查文件中的行是否与正则表达式匹配,如果匹配, filter()
然后检查该行中的“数字”是否与您的input
匹配,即String.valueOf(washCard.getCardID())
。
count()
计算filter()
返回的流中的所有元素, count()
返回long
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.