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.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)



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

                                                                     if (indexfound>-1)



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




int idx=0;

StringTokenizer st= new StringTokenizer(line);

tokencount= st.countTokens();


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

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










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(
    and prints the keyword in it using arraylist.


Leave a Reply

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

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

Twitter picture

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

Facebook photo

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

Connecting to %s