How to find occurence of a string in a file

Single occurrence
This java program helps to find the occurrence of a string in a file. It will print the location of the string in the console as output. You can use this program as append with the web application you developing or as a separate stand alone program

Expected input : file name, Search String

Code:
Given the utility method only

public void searchString(String fileName, String  searchText) {
StringBuilder sb = new StringBuilder();
String  line=null;
try {
BufferedReader reader =new BufferedReader(new  FileReader(fileName));

//Reads until the end-of-file met
while( null  != ( line = reader.readLine() ) ){

//Read line-by-line  directly
sb.append(reader.readLine());
}
} catch (IOException ex)  {
ex.printStackTrace();
}
String fileText =  sb.toString();
System.out.println("Position in file : " +  fileText.indexOf(searchText));

}
multiple occurrence of the String in a file
By fine tuning the above program you can find the multiple occurrence of the String in a file by using the method given below. The input for the program is the individual lines getting from the file using the method readLine()



private Boolean  ifWordsExists(String line, String searchText, SearchBean fo) throws IOException  {
StringBuffer bf = null;
int index = 0;
Boolean flag = false;
if  (line.indexOf(searchText) > -1) {
flag = true;

}
return  flag;
}
Here it will returns the value true if the string find in the line supplied. And after setting the founded line in array list you can display it on the web application

Comments