Friday, August 28, 2015

JAVA : Count no. of occurence of string from file

Use below JAVA code to find the number of occurrence of string from file.Before that you need to download the "commons.io" jar and "commons.lang" jar from apache website. This code works only with text document and html files. Try other type files at your risk.

Java Code for Single File:

import java.io.File;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;

public class StrOccurCount {
     public static void main(String[] args) {
          try {
               String SFilePath          = "d://";
               String SFileName         = SFilePath+"Hai.txt";
               String SSearchText       = "text";

               String str              = FileUtils.readFileToString(new File(SFileName));
               str                        = StringUtils.lowerCase(str);
               int iCount              = StringUtils.countMatches(str, SSearchText);

               System.out.println("File : "+SFileName+", Count : "+iCount);
          } catch(Exception ex) {
               ex.printStackTrace();
          }
    }
}

Incase you want to count occurrence of string from all files from the folder, use the below code.

Java Code for Multiple Files:

import java.io.File;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;

public class StrOccurCountAll {
     public static void main(String[] args) {
          try {
               String SFilePath        = "d://SearchFolder//";
               String SSearchText      = "text";

               File theFolder          = new File(SFilePath);
               File[] theFileList      = theFolder.listFiles();

               for(int i=0; i<theFileList.length; i++) {
                    String SFileName        = SFilePath+theFileList[i].getName();

                    String str              = FileUtils.readFileToString(new File(SFileName));
                    str                        = StringUtils.lowerCase(str);
                    int iCount              = StringUtils.countMatches(str, SSearchText);

                    System.out.println(SFileName+" : "+iCount);
               }
          } catch(Exception ex) {
               ex.printStackTrace();
          }
    }
}