Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Find line number in text file

807580Feb 11 2010 — edited Feb 11 2010
Hi all,

I need to find the line numbers on a file where a particular string matches.

for example:

A lazy cat
A strong cat and it is black
Black is not good

So I will match for the word black and it will give the numbers say line 2 and 3 it found the match.

I am using the code:
try{
    // Open the file that is the first
    // command line parameter
      FileInputStream fstream = new FileInputStream("c:\\test.log");
    // Get the object of DataInputStream
      DataInputStream in = new DataInputStream(fstream);
      BufferedReader br = new BufferedReader(new InputStreamReader(in));
      String strLine;

     String[] arr= null;

    
    //Read File Line By Line

   String regex = "black"; 

   while ((strLine = br.readLine()) != null)   {
    // Split the sentence into strings based on space
       arr = strLine.split("\\s");
   if (arr[0].equalsIgnoreCase("black"))
      System.out.print("match found");

    Pattern p = Pattern.compile(regex);
    Matcher m = p.matcher(strLine);
Thanks in advance.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Mar 11 2010
Added on Feb 11 2010
3 comments
761 views