extract matched line from text file

眉间皱痕 提交于 2019-12-08 11:52:38

问题


a:b:c:d:e

bb:cc:dd:ee:ff

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

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.


回答1:


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();


来源:https://stackoverflow.com/questions/16255231/extract-matched-line-from-text-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!