Java reads and writes files, searches for content in a file, and outputs all rows containing that content

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.