1. Description of the problem
Look for a txt or Java file in a directory and subdirectories to search for all the lines of the word "object".
Searches all files in the D drive for rows containing "objects".
2. Solving Ideas
Find out all the files on the D drive first.
Then, for each line of content in each file, search, if it contains the word "object", output the line.
3. Program code
ImportJava.io.File;Importjava.io.IOException;ImportJava.util.Scanner; Public classB {Static intM=1; Static voidSearch (File a,string x)throwsioexception{//find x in each line in file aScanner scan =NewScanner (A, "GBK")); intK = 0; while(true){ if(Scan.hasnext () = =false) Break; String s=Scan.nextline (); K++; if(S.contains (x)) {String SS=m + ". File:" + a.getpath () + "+" + k + "line \ n Content:" +s; SYSTEM.OUT.PRINTLN (ss); M++; }} Scanner Scan1=NewScanner (A, "utf-8")); intK1 = 0; while(true){ if(Scan1.hasnext () = =false) Break; String S1=Scan1.nextline (); K1++; if(S1.contains (x)) {String SS1=m + ". File:" + a.getpath () + "first" + k1 + "line \ n Content:" +S1; System.out.println (SS1); M++; } } } Static voidF (File a,string s)throwsioexception{//find rows with s in all files under afile[] FF=A.listfiles (); if(ff==NULL)return; for(File it:ff) {if(It.isfile ()) {//If a is a file, search directlysearch (it,s); } if(It.isdirectory ()) {//If A is a directory, continue to find the directory or file under its directoryf (it,s); } } } Public Static voidMain (string[] args)throwsIOException {f (NewFile ("d:\\"), "Object"); }}
4. Run the result diagram
, a total of 198 lines in all documents under the D drive contain the word "object".
Java reads and writes files, searches for content in a file, and outputs all rows containing that content