Saturday 5 March 2011

Find occurance of SearchString in Files - Recursively for all sub-folders too.

Hi Friends ,

This is bit of small utility program that can used to search items & record its counts for each file in a folder &  recursively all files in it's subfolder too ...

Suppose I have my project source at folder D:\project\src.
This src folder lots of sub folders/packages which in urn have lots of java files/ jsp / properties / xml etc ...

Now suppose, I want to find the occurance of "Connection", "Statement","ResultSet" , in each files of the project's java source  & get it neatly to an xls file .. how do you do it ??

The below program tries to achieve the same but in crude manner ... it  uses core Java , file handling & Regex functionality to achieve this ...


 File Name ConnectionStatementResultSettrycatchfataldebugthrow
D:\project\src\com\xyz\cash\dao\AAbstractDAO.java52461028491310899
D:project\src\com\xyz\cash\dao\AEntity.java40012250044
D:\project\src\com\xyz\cash\dao\Batch.java780330515


Thanks

Rakesh

/**
 *
 * @author rakesh.praphullan
 */
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class RegexTest {
    static String fileExtn = ".java";
    static String checkDir = "D:\\project\\src";
    static String logFile = "D:\\project\\Result_log.xls";
   
    static String[] searchStrings = {"Connection", "Statement","ResultSet","try","catch","fatal","debug","throw"};  
    private static StringBuffer logBuffer = new StringBuffer();
    private static StringBuffer csvBuffer = new StringBuffer();
    public static void logMessage(String s) {
        //logBuffer.append("" + s + "\n");
       
        System.out.println(s);
    }
   
    public static void csvMessage(ArrayList list) {
        //csvBuffer.append("");
        int size = list.size();
        for (int i = 0; i < size; i++) {
       
            String value = (String)list.get(i);
            //System.out.println("value is "+value);
            csvBuffer.append( value+ "\t");
        }
        //logBuffer.append("" + s + "\n");
        csvBuffer.append("");
        csvBuffer.append("\n");
        //System.out.println(s);
    }
    public static void csvHeader(String[] s) {
        csvBuffer.append(" File Name "+ "\t");
        for (int i = 0; i < s.length; i++) {
            csvBuffer.append(s[i] + "\t");
        }
        //logBuffer.append("" + s + "\n");
        csvBuffer.append("");
        csvBuffer.append("\n");
        //System.out.println(s);
    }
    public static void main(String[] args) {
        try{
            csvHeader(searchStrings);
        File dir = new File(checkDir);
        if (dir.isDirectory()) {
            File[] files = dir.listFiles();
            for (int i = 0; i < files.length; i++) {
                File file = files[i];
                if (file.isDirectory()) {
                    handleDir(file);
                } else {
                    handleFile(file);
                }
            }
        }
        }finally{
            try {
                writeFile(logFile, csvBuffer);
            } catch (Exception ex) {
                Logger.getLogger(RegexTest.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    private static void handleDir(File dir) {
       
        File[] files = dir.listFiles();
            for (int i = 0; i < files.length; i++) {
                File file = files[i];
                if (file.isDirectory()) {
                    handleDir(file);
                } else {
                    handleFile(file);
                }
            }
    }
    private static void handleFile(File fileName) {
       
        if ( fileName != null)
        {
            int index = -1;
            index = fileName.getName().indexOf(fileExtn);
            if( index == -1){ return ; }
        }
        //fileName.
        StringBuffer buff = readFile(fileName);
        String path = fileName.getAbsolutePath();
        String name = path ;
        //logMessage("Inside handleFile "+name);
        int count[] = new int[searchStrings.length];
        for (int i = 0; i < searchStrings.length; i++) {
            count[i] = 0;
            String data = searchStrings[i];
            Pattern pattern = Pattern.compile(data);
            Matcher matcher =
                    pattern.matcher(buff.toString());
            boolean found = false;
            while (matcher.find()) {
                /*System.out.println("Found in File ["+name+"] the text " + matcher.group() + " starting at " +
                        "index " + matcher.start() + " and ending at index " + matcher.end());*/
                found = true;
                count[i]++;
            }
            if (!found) {
                //System.out.println("No match found for " + data+" in File "+name);
            }
        }
        // Final Analysis
        ArrayList list = new ArrayList();
        list.add(name);
        logMessage("Analysis of  File :["+name+"]");
        for (int i = 0; i < searchStrings.length; i++) {
            list.add(""+count[i]);
            if(count[i] != 0)
            {
                logMessage(" Seaarch item :["+searchStrings[i]+"] found ["+count[i]+"] times");
            }
        }
        csvMessage(list);
    }
    private static StringBuffer readFile(File filename) {
        StringBuffer buff = new StringBuffer();
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(filename);
            char current;
            while (fis.available() > 0) {
                current = (char) fis.read();
                buff.append(current);
            }
        } catch (IOException ex) {
            Logger.getLogger(ClassPathPrinter.class.getName()).log(Level.SEVERE, null, ex);
            logMessage(ex.toString());
        } finally {
            try {
                fis.close();
            } catch (IOException ex) {
                Logger.getLogger(ClassPathPrinter.class.getName()).log(Level.SEVERE, null, ex);
                logMessage(ex.toString());
            }
        }
        //System.out.println("Filecontent is  :" +buff.toString());
        return buff;
    }
    private static boolean writeFile(String filename, StringBuffer buff) throws Exception {
        boolean writeDone = false;
        FileOutputStream fout = null;
        try {
            fout = new FileOutputStream(filename);
            String data = buff.toString();
            char current;
            for(int i=0 ; i< data.length(); i++)
            {
                fout.write(data.charAt(i));
            }
            writeDone = true;
        } catch (IOException ex) {
            Logger.getLogger(RegexTest.class.getName()).log(Level.SEVERE, null, ex);
            logMessage("IOException"+ex+"");
            throw ex;
        } finally {
            try {
                fout.close();
            } catch (IOException ex) {
                Logger.getLogger(RegexTest.class.getName()).log(Level.SEVERE, null, ex);
                logMessage("IOException"+ex+"");
                throw ex;
            }
        }
        return writeDone;
    }
}

 

No comments:

Post a Comment