Wednesday, February 2, 2011

Search String in a file

This program will help you to search the string from the file.Just go through the program you can easily understand.
Here i used command line argument to search string in the file.You can replace the args[i] in the program to meet your requirement.
import java.io.*;
public class stringSearcher {
 public static void main(String args[]) {
  try {
   //Give your file path here.
    File file = new File("C:\\Documents and Settings\\" +
                          "sriram\\Desktop\\workspace.txt");
    BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
    int linecount = 0;
    String line;
    while((line=bufferedReader.readLine())!= null) {
     /*
      * Here Searching word is passed using command line argument.
      * Replace the args[i] in stringFound to the actual string you are looking for.
      * you can pass the value from properties file also.
      * According to your requirement you change it.
      */
      int length = args.length;
      for(int i=0;i -1) {
        System.out.println("At "+stringFound+" Searching word...."+args[i]+"...found in fileName***"+file.getName());
       } else {
        System.out.println("Searching word..."+args[i]+"...not found in fileName***"+file.getName());
       }
      }
     }
    bufferedReader.close();
   }
  catch (IOException excep) {
   System.out.println("Exception occured***"+ excep.toString());
   }
  }
 }
For more java programming click this Link.