Java Basic Problems

Java: How to Read a text file and search any specific word from that

In my last post I have given an idea about  How to change font of JLabel.

Here, I have shared   Reading a text file and search any specific word from that.

Sometimes we may need to search any specific word from a text file. For this, we need to know how to read a text file using java.

Here I have given a simple way, just read a text file and find out the search keyword, after finding out the search key word it will be shown on which line the searched keyword was found.

 ** It will give you just a basic idea.

Click Here to download the Code+Reader1.txt  to test yourself.

Code Example:

import java.io.*;

import java.util.*;

class filereader

{

public static void main(String args[]) throws Exception

   {

   int tokencount;

   FileReader fr=new FileReader(“reader1.txt”);

   BufferedReader br=new BufferedReader(fr);

   String s;

   int linecount=0;

   String line;

   String words[]=new String[500];

                                while ((s=br.readLine())!=null)

                                        {

                                        linecount++;

                                        int indexfound=s.indexOf(“see”);

                                                                     if (indexfound>-1)

                                                                     {

 System.out.println(“\n”);

 System.out.println(“Word was found at position::” +indexfound+ “::on line”+linecount);

System.out.println(“\n”);

 line=s;

System.out.println(line);

int idx=0;

StringTokenizer st= new StringTokenizer(line);

tokencount= st.countTokens();

System.out.println(“\n”);

System.out.println(“Number of tokens found” +tokencount); System.out.println(“\n”);                                             

 for (idx=0;idx<tokencount;idx++)                                                                                                    {

 words[idx]=st.nextToken();

System.out.println(words[idx]);

                                                           }

                                                            }

                                        }

   fr.close();

   }

}

OUTPUT:

file reader java

5 thoughts on “Java: How to Read a text file and search any specific word from that”

  1. Sir, i am trying a program but i m not getting it
    A java program that reads a source code file(file.java)
    and prints the keyword in it using arraylist.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s