从文本文件中提取匹配的行 [英] extract matched line from text file
本文介绍了从文本文件中提取匹配的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
a:b:c:d:e
bb:cc:dd:ee:ff
bb:cc:dd:ee:ff
ccc:ddd:eee:fff:ggg
ccc:ddd:eee:fff:ggg
我上面有一个文本文件内容.我正在尝试将我的用户输入与文本文件进行比较.例如
I have a textfile content above. I am trying to compare my user input with the text file. For example
cc:dd
找到后,我需要检索整行.如何检索用户输入的行?我尝试使用 while(scanner.hasNext())
但我无法得到我想要的结果.
When it is found, I need to retrieve the entire line. How can I retrieve the line which my user input? I have tried using while(scanner.hasNext())
but I could not get my desire outcome.
推荐答案
使用标准 Java 库:
With standard Java libraries:
File file = new File("file.txt");
String word = "abc";
Scanner scanner = null;
try {
scanner = new Scanner(file);
} catch(FileNotFoundException e) {
//handle this
}
//now read the file line by line
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if(line.contains(word)) {
System.out.println(line);
}
}
scanner.close();
这篇关于从文本文件中提取匹配的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文