Happy Codings - Programming Code Examples
Html Css Web Design Sample Codes CPlusPlus Programming Sample Codes JavaScript Programming Sample Codes C Programming Sample Codes CSharp Programming Sample Codes Java Programming Sample Codes Php Programming Sample Codes Visual Basic Programming Sample Codes


Java Programming Code Examples

Java > Core Java Code Examples

Count total number of occurences of a String in a text file

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
Count total number of occurences of a String in a text file import java.io.File; import java.io.BufferedReader; import java.io.FileReader; import java.util.StringTokenizer; public class WordCounter { public static void main(String args[]) throws Exception { if(args.length != 1) { System.out.println("Invalid number of arguments!"); return; } String sourcefile = args[0]; String searchFor = "good bye"; int searchLength=searchFor.length(); String thisLine; try { BufferedReader bout = new BufferedReader (new FileReader (sourcefile)); String ffline = null; int lcnt = 0; int searchCount = 0; while ((ffline = bout.readLine()) != null) { lcnt++; for(int searchIndex=0;searchIndex<ffline.length();) { int index=ffline.indexOf(searchFor,searchIndex); if(index!=-1) { System.out.println("Line number " + lcnt); searchCount++; searchIndex+=index+searchLength; } else { break; } } } System.out.println("SearchCount = "+searchCount); } catch(Exception e) { System.out.println(e); } } }