Heading

Thursday, February 27, 2014

Searching for a string or substring in list of files in a folder

package Examp;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Fileex {
public static void main(String[] args) throws IOException {
   
    String path = "G:\\test\\",a[]=new String[50],s;
    boolean flag=false;
    int j;

    System.out.println("Enter One String to search content in files");
       
    BufferedReader br1=new BufferedReader(new InputStreamReader(System.in));
    s=br1.readLine();

    File folder = new File(path);
    File[] listOfFiles = folder.listFiles();
   
    for(int i=0;i<listOfFiles.length;i++)
    {
        String file=listOfFiles[i].getName();
        BufferedReader br = new BufferedReader(new FileReader("G:\\test\\"+file));
        try {
          
             String line;
             j=0;
             flag=false;
            while ((line = br.readLine()) != null)
            {
                 StringTokenizer st = new StringTokenizer(line);
                while (st.hasMoreTokens())
             {
                    if(s.equalsIgnoreCase(st.nextToken())||line.contains(s))
                    {
                        flag=true;
                    }

                }
                if(flag)
                {
                   a[j]=line;
                  
                }
                 j++;
        }
            if(flag)
            {
                System.out.println(file);
                System.out.println("*********************");
                for(int k=0;k<j;k++)
                {
                    System.out.println(a[k]);
                }
                System.out.println("*********************");
               
               
            }

          }
          catch (Exception e)
        {
                System.out.println("can't open the specified file");
        }
          finally
        {
                br.close();
                   }

    }

    if(!flag)
        {
            System.out.println("no such file available" );
        }
   
  }
}
OutPut:

Enter One String to search content in files
maTHS
maths.txt
*********************
maths is my favourate subject
i studied it when am at SSc
*********************

_________________________________________________
Enter One String to search content in files
sharma
no such file available

 

No comments:

Post a Comment