Question: Given a file and a string, determine whether the file contains the string. If so, print the row number containing the string and all the content of the row. Idea: ① use BufferedReader to read files and define the initial row number as 0. ② Traverse and judge each row of the file. If the row number and row content are included, they are stored in hashMap. The row number is used as the key and the row content as the value. Finally, the following code is implemented by traversing hashMap:
Package com. sgl. io; import java. io. bufferedReader; import java. io. fileReader; import java. util. hashMap; import java. util. iterator; import java. util. map; import java. util. map. entry; public class FileFindString {public static void findStringInFile (String fileName, String subStr) throws Exception {BufferedReader br = new BufferedReader (new FileReader (fileName); Map <Integer, string> res = new HashMa P <> (); int lineNum = 0; // record line number String line; while (line = br. readLine ())! = Null) {lineNum ++; // The first type: contains // if (line. contains (subStr) {// res. put (lineNum, line); // ''} // Second: indexOf if (line. indexOf (subStr )! =-1) {res. put (lineNum, line) ;}// traverse hashMap. The key is the row number, and the value is the string if (res. isEmpty () {System. out. println ("file [" + fileName + "] does not contain [" + subStr + "] substring");} else {Iterator <Entry <Integer, string> it = res. entrySet (). iterator (); while (it. hasNext () {Entry <Integer, String> entry = it. next (); System. out. println ("th" + entry. getKey () + "row: \ t" + entry. getValue () ;}} br. close () ;}public static void main (String [] args) throws Exception {findStringInFile ("test1.txt", "time ");}}
Test files: