Finding a word in a file java

I am trying to search a string in a file in java and this is what, I tried . In the below program I am getting output as No Data Found and I am sure that the file has the word which I am searching

import java.io.*;
import java.util.Scanner;

public class readfile {
    static String[] list;
    static String sear = "CREATE";

    public void search() {
        Scanner scannedFile = new Scanner("file.txt");

        while (scannedFile.hasNext()) {
            String search = scannedFile.next();
            System.out.println("SEARCH CONTENT:"+search);

            if (search.equalsIgnoreCase(sear)) {
                System.out.println("Found: " +search);
            } 
            else  {
                System.out.println("No data found.");
            }
        }
    }

    public static void main (String [] args) throws IOException {
        readfile read = new readfile();
        read.search();
    }
}

Tim Biegeleisen's user avatar

asked Sep 21, 2015 at 9:23

krisshi's user avatar

3

Don’t do:

search.equalsIgnoreCase(sear)

Try:

search.toUpperCase().contains(sear)

I think the search is the whole String of the File, so you never would become true with equals.

answered Sep 21, 2015 at 9:28

Tilo's user avatar

TiloTilo

5956 silver badges14 bronze badges

Use nextLine() instead of next() and then use split. Like this :

What’s the difference between next() and nextLine() methods from Scanner class?

Difference :

next() can read the input only till the space. It can’t read two words separated by space. Also, next() places the cursor in the same line after reading the input.

nextLine() reads input including space between the words (that is, it reads till the end of line n). Once the input is read, nextLine() positions the cursor in the next line.

Use following code :

   String search = scannedFile.nextLine();
   String[] pieces = data.split("\s+");

  for(int i=0; i<pieces.length(); i++)
  {
          if(pieces[i].equalsIgnoreCase(sear))
        {
            System.out.println("Found: " +search);
        } 
        else 
        {
            System.out.println("No data found.");
        }
   }

Community's user avatar

answered Sep 21, 2015 at 9:34

Sagar Joon's user avatar

Sagar JoonSagar Joon

1,36714 silver badges23 bronze badges

Ok, here is my understanding of your program.

You search in the file file.txt the word CREATE.
To do so, you read each word in the file and if it is CREATE you print Found create.

The issue here is that for every word in the file, if it isn’t CREATE you print No data found.

Instead you should wait for the end of the file and then if you haven’t found it you will print the error message.

answered Sep 21, 2015 at 9:33

vincent lefrere's user avatar

Try this :

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class readfile {
    static String[] list;
    static String sear = "CREATE";

    public void search() throws IOException {

        List<String> saveAllLinesForRewriting = new ArrayList<String>();

        // Need to read file line by line
        BufferedReader bufferedReader = new BufferedReader(new FileReader("file.txt"));
        String saveLine;
        while ((saveLine = bufferedReader.readLine()) != null) {
            saveAllLinesForRewriting.add(saveLine);
        }
        bufferedReader.close();

        // Check if your word exists
        if (saveAllLinesForRewriting.toString().contains(sear)) {
            System.out.println("Found: " + sear);
        } else {
            System.out.println("No data found.");
        }
    }

    public static void main(String[] args) throws IOException {
        readfile read = new readfile();
        read.search();
    }
}

answered Sep 21, 2015 at 9:47

FullStack's user avatar

FullStackFullStack

66510 silver badges26 bronze badges

1

Instead of reading file using scanner, first create a file resource to read by adding the below line

File file = new File("Full Path of file location");

before

Scannner scannedfile = new Scanner("file.txt");

and change the above line to

Scanner scannedfile = new Scanner(file);

rest your code is working fine.

answered Sep 21, 2015 at 9:49

amit28's user avatar

amit28amit28

1768 bronze badges

The problem is that the scanner is scanning the String «file.txt» and not the file.

To fix this you have to do what amit28 says. Your finally code is as follows

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;

public class readfile {
    static String[] list;
    static String sear = "CREATE";

    public void search() {

        File f = new File("file.txt");
        Scanner scannedFile;
        try {
            scannedFile = new Scanner(f);

            while (scannedFile.hasNext()) {
                String search = scannedFile.next();
                System.out.println("SEARCH CONTENT:"+search);

                if (search.equalsIgnoreCase(sear)) {
                    System.out.println("Found: " +search);
                } 
                else  {
                    System.out.println("No data found.");
                }
            }

        } catch (FileNotFoundException e) {
            // FIXME Auto-generated catch block
            e.printStackTrace();
        }






    }

    public static void main (String [] args) throws IOException {
        readfile read = new readfile();
        read.search();
    }
}

answered Sep 21, 2015 at 9:57

Antonio's user avatar

AntonioAntonio

3894 silver badges12 bronze badges

Following Java example program used to search for the given word in the file.

Step 1: Iterate the word array.

Step 2: Create an object to FileReader and BufferedReader.

Step 3: Set the word wanted to search in the file. For example,

String input=”Java”;

Step 4: Read the content of the file, using the following while loop

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

Step 5: Using equals() method the file words are compared with the given word and the count is added.

Step 6: The count shows the word occurrence or not in the file.

FileWordSearch.java

package File;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class FileWordSearch 
{
   public static void main(String[] args) throws IOException 
   {
      File f1=new File("input.txt"); //Creation of File Descriptor for input file
      String[] words=null;  //Intialize the word Array
      FileReader fr = new FileReader(f1);  //Creation of File Reader object
      BufferedReader br = new BufferedReader(fr); //Creation of BufferedReader object
      String s;     
      String input="Java";   // Input word to be searched
      int count=0;   //Intialize the word to zero
      while((s=br.readLine())!=null)   //Reading Content from the file
      {
         words=s.split(" ");  //Split the word using space
          for (String word : words) 
          {
                 if (word.equals(input))   //Search for the given word
                 {
                   count++;    //If Present increase the count by one
                 }
          }
      }
      if(count!=0)  //Check for count not equal to zero
      {
         System.out.println("The given word is present for "+count+ " Times in the file");
      }
      else
      {
         System.out.println("The given word is not present in the file");
      }
      
         fr.close();
   }


}

Output:

The given word is present for 2 Times in the file

Hey everyone! In this article, we will learn how to find a specific word in a text file and count the number of occurrences of that word in the text file. Before taking a look at the code, let us learn about BufferedReader class and FileReader class.

FileReader class in Java


FileReader class is used for file handling purposes in Java. It reads the contents of a file in a stream of characters. It is present in the java.io package. It reads the contents into a character array.

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

BufferedReader class in Java


The BufferedReader class in Java is used to read contents from a file in Java. It is used to read text from the input stream in Java. It is present in the java.io.BufferedReader package in Java. It buffers the character read into an array.

BufferedReader bfr = new BufferedReader(fr);

Java Program to find a specific word in a text file and print its count.


import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.util.Scanner;


public class Program 
{
   public static void main(String[] args) throws Exception 
   {
      int cnt=0;
      String s;
      String[] buffer; 
      File f1=new File("file1.txt"); 
      FileReader fr = new FileReader(f1);
      BufferedReader bfr = new BufferedReader(fr);
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the word to be Searched");
      String wrd=sc.nextLine();
       
           

      while((s=bfr.readLine())!=null)   
      {
         buffer=s.split(" ");  
          for (String chr : buffer) 
          {
                 if (chr.equals(wrd))   
                 {
                   cnt++;    
                 }
          }
      }
      if(cnt==0)  
      {
         System.out.println("Word not found!");
      }
      else
      {
         System.out.println("Word : "+wrd+"found! Count : "+cnt);
      }
      
         fr.close();
   }


}
Output:-

Enter the word to be Searched krishna
Word : krishnafound! Count : 4

I hope this article was useful to you!
Please leave a comment down below for any doubt/suggestion.

Also read: QR Code to Text converter in Java

This tutorial explains how to read a text file and search any specific word in java. In order to search any specific word from a text file, we need to first read text file. Here we have provided simple example for reading a text file and search any specific word from that.

How to read a text file and search any specific word in java

sample.txt
we are going to use below text file content using java code.

Simple Form Validation In Reactjs Example
Create a Dropdown Menu using ReactJS
Installing React Native on Windows Tutorial
Create Dropdown Menu In React Native
How To Customize Button In React Native
Facebook loading animation using CSS3
Facebook Style Chat Application with jQuery and CSS
Append Or Prepend HTML Using ReactJS
Create Ripple Animation Effect Using Css
Ripple Effect Animation On Button Click With CSS3

FileWordSearch.txt

package demo;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class FileWordSearch {

 public static void main(String[] args) throws IOException {
  // TODO Auto-generated method stub

  String[] words = null; // Intialize the word Array

  // Creation of File Descriptor for input file
  File f1 = new File("sample.txt");

  // Creation of File Reader object
  FileReader fr = new FileReader(f1);

  // Creation of BufferedReader object
  BufferedReader br = new BufferedReader(fr);

  String s;
  String input = "Facebook"; // Input word to be searched
  int count = 0; // Intialize the word to zero

  // Reading Content from the file
  while ((s = br.readLine()) != null) {
   words = s.split(" "); // Split the word using space
   for (String word : words) {
    if (word.equals(input)) { // Search for the given word
     count++; // If Present increase the count by one
    }
   }
  }
  if (count != 0) { // Check for count not equal to zero
   System.out.println("The given word is present for " + count
     + " Times in the file");
  } else {
   System.out.println("The given word is not present in the file");
  }

  fr.close();

 }
}

Output:-
——————

This is all about Java Program to Search for a given word in a File. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.

In this tutorial, you will learn how to Search for a Particular Word in a File in java. To understand it better, you may want to check the following first:

  • File in Java

First, save the content in a text file with the same name that you enter in a program. For this example, a text file saved with the name javaCode.txt

javaCode.txt

Welcome to Simple2Code.
Let Start
first tutorial
second Program

Source Code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

//search the particular word in a file

import java.io.*;

public class SearchWord

{

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

  {

      File f = new File(«javaCode.txt»); //file

      String[] words=null;  //Intialization

      FileReader fr = new FileReader(f);  //File Reader object

      BufferedReader br = new BufferedReader(fr);

      String s;    

      String input=«program»;

      int count=0;   //Intializing count

      while((s = br.readLine())!=null) //Reading Content from the file

      {

        words=s.split(» «);  //Split the word using space

          for (String word : words)

          {

            if (word.equals(input))  //Search for the given word

            {

              count++;    //If Present increase the count by one

            }

          }

      }

      if(count!=0)  //Check for count not equal to zero

      {

        System.out.println(«Number of times given word present: «+count);

      }

      else

      {

        System.out.println(«The given word is not present.»);

      }

        fr.close();

  }

}

Output:

Number of times given word present: 3


MORE

Find the output ab, cd, ef, g for the input a,b,c,d,e,f,g in Javascript and Python

In this tutorial, we will write a program to find a pairs of elements from an array such that for the input [a,b,c,d,e,f,g] we will …
Read More

Half Pyramid of Alphabets in C

In this tutorial, we will learn and code alphabet patterns in C programming language specifically the Half pyramid of alphabets in C programming. However, in …
Read More

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

File handling can be a bit daunting to the beginner. We all know what a file is, but how to access and use even the simplest text files through a program can make our brains go to mush. That is because programs see files as streams of data. It opens access to a file and pulls in that data as a stream in either chunks or in a serial (single file) type of style… one character or byte or bit at a time. Most beginners to Java have no clue where to even begin. Well Dream.In.Code and Martyr2 to the rescue! As super heroes, we fight the baddies which cause confusion and mayhem and bring you the straight scoop. So worry not programming citizen, we are on the job in this episode of the Programming Underground! Up Up and Awayyyyyy!

“It is a bird! It is a plane! No it is a text file! Say what?” Sure the topic of files doesn’t necessarily fit easy in that memorable phrase, but using our handy Java utility belt I am sure we can open up that file, read its contents and find what lurks inside. In this example we will be creating a small program which opens a standard text file and searches for a word or phrase we provided at runtime as a parameter. The user will be able to type something like java searchfile “hello” and it will search our text file for the phrase “hello” and return the position and line number where the word appears.

We do this by opening up a file using a specialized Java class called a “BufferedReader”. This class is designed to open a file and create a stream of data (buffered) for us to then read from and use. To get the process started we will give it a plain FileReader object initialized with a file that we want to search. For simplicity sake I hardcoded this value in the program but you could easily use another parameter for the filename to search. I will leave that part up to you.

So once we have this file open we begin the process of reading through the file line by line. We will do this using a while loop that reads the line, checks if anything was read, then begins our most basic search on that line. The process looks like this…

// Need the input/output package when handling files.
import java.io.*;

public class searchfile {
	public static void main(String args[]) {

		// Check to see if they supplied the search phrase as a parameter.
		// If so, set our searchword from the parameter passed and begin searching.
		if (args.length > 0) {

			// Set the searchword to our parameter 
			// (eg if they type 'java searchfile "hello"' then the search word would be "hello")
			String searchword = args[0];
		 
			try {

				// Keep track of the line we are on and what the line is.
				int LineCount = 0;
				String line = "";


				// Create a reader which reads our file. In this example searchfile.txt is the file we are searching.
				BufferedReader bReader = new BufferedReader(new FileReader("c:\searchfile.txt"));


				// While we loop through the file, read each line until there is nothing left to read.
				// This assumes we have carriage returns ending each text line.

				while ((line = bReader.readLine()) != null) {
					LineCount++;

					// See if the searchword is in this line, if it is, it will return a position.
					int posFound = line.indexOf(searchword);


					// If we found the word, print the position and our current line.
					if (posFound > - 1) {
						System.out.println("Search word found at position " + posFound + " on line " + LineCount);
					}	
				}

		
				// Close the reader.
				bReader.close();

			}
			catch (IOException e) {
				// We encountered an error with the file, print it to the user.
				System.out.println("Error: " + e.toString());
			}
		}
		else {
			// They obviosly didn't provide a search term when starting the program.
			System.out.println("Please provide a word to search the file for.");
		}
	}
}

Our supplied parameter to this program is going to come into the program through the args[] array. If you have ever wondered what that args[] array was for, now you know. We check this array first to see if the user supplied us a search keyword/phrase for us to find. No use conducting the search if there is no word to search for. Once we have it, then we can move onto the reading of the file and our hunt for the elusive search word (them baddies like to hide in the dark alleys you know).

The key part of this program is that while loop. By calling the BufferedReader’s readLine() method we read in a line of the text file and store it in our variable called “line”. We then compare this to “null” to see if indeed something was read. Once we hit the end of the file, this will lead to a null value which will end the loop.

Now that we have our line read in from the text file, we use the string class’ indexOf() method to locate the word within the line. The value returned by this method is the position (starting at index 0) of the search word in our current line. If the word is not found, it will return a value of -1. Obviously we can test to see if the value is higher than -1 (meaning it found the word) and print the position of that word and the line we found it on. The line count of course is incremented each time we read a line to keep track of where in the file we are at.

The results of this program should look something similar to this…

c:>java searchfile "hello"
Search word found at position 0 on line 1
Search word found at position 9 on line 4
Search word found at position 12 on line 5

So the results tell us that it had found the word “hello” three times on lines 1, 4 and 5 at positions 0, 9, and 12 respectively. Now this program is very basic and would work on text files that are setup to have each line terminated by a carriage return. The method readLine() will read a line until it hits this carriage return. Another limitation to this program is that it will only find the first match of each line. So lets say on the first line you had two “hello” words. It would only detect the first one at position 0 and not the second at position 13.

You could solve this limitation by putting in another loop inside the while loop (once you have determined that indexOf() was not -1) and would loop until indexOf() equals -1. This would be a simple addition that you could make if you were interested in not only finding out if the line had the word, but all locations of the word in the text.

Of course this search method can slow down for huge text files since we are doing a sequential process of the file. So for experimental purposes I suggest that you start with a file that has no more than a few hundred lines and then expand it when you want to do some serious processing. If the text file gets too big, you might want to look at an indexed approach. Maybe we will cover this in another entry… who knows!

Read through the in-code comments of the example above and see how this is put together. Each step has been documented so that you can put the pieces together and come up with an idea of what the program is doing. Feel free to edit the code as you see fit and make whatever modifications you want to it. Just keep in mind this is ideal searching for text files and not exactly what you want to do for binary files. Those baddies will have to be handled another day. After all, the super criminals are not easily caught!

So the next time you are in a dark room at night and no where else to turn for learning file handling in Java, have no fear, DIC and Martyr2 is here! Thank you for reading! 🙂

About The Author

Martyr2 is the founder of the Coders Lexicon and author of the new ebooks «The Programmers Idea Book» and «Diagnosing the Problem» . He has been a programmer for over 25 years. He works for a hot application development company in Vancouver Canada which service some of the biggest tech companies in the world. He has won numerous awards for his mentoring in software development and contributes regularly to several communities around the web. He is an expert in numerous languages including .NET, PHP, C/C++, Java and more.

Following Java program accepts a String value from the user, verifies whether a file contains the given String and prints the number of occurrences of the word too.

Example

 Live Demo

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FindingWordFromFile {
   public static void main(String args[]) throws FileNotFoundException {
      //Reading the word to be found from the user
      Scanner sc1 = new Scanner(System.in);
      System.out.println("Enter the word to be found");
      String word = sc1.next();
      boolean flag = false;
      int count = 0;
      System.out.println("Contents of the line");
      //Reading the contents of the file
      Scanner sc2 = new Scanner(new FileInputStream("D:sampleData.txt"));
      while(sc2.hasNextLine()) {
         String line = sc2.nextLine();
         System.out.println(line);
         if(line.indexOf(word)!=-1) {
            flag = true;
            count = count+1;
         }
      }
      if(flag) {
         System.out.println("File contains the specified word");
         System.out.println("Number of occurrences is: "+count);
      } else {
         System.out.println("File does not contain the specified word");
      }
   }
}

Output

Enter the word to be found
the
Contents of the line
Tutorials Point originated from the idea that there exists a class of readers who respond better 
to online content and prefer to learn new skills at their own pace from the comforts of their drawing rooms.
The journey commenced with a single tutorial on HTML in 2006 and elated by the response it generated, 
we worked our way to adding fresh tutorials to our repository which now proudly flaunts a wealth of 
tutorials and allied articles on topics ranging from programming languages to web designing to academics and much more.
40 million readers read 100 million pages every month
Our content and resources are freely available and we prefer to keep it that way to encourage our readers
 acquire as many skills as they would like to. We don’t force our readers to sign up with us or submit 
their details either. No preconditions and no impediments. Simply Easy Learning!
File contains the specified word
Number of occurrences is: 3

To Search a word in in list of files available in Folder, you need to find the list of files first and then scan each and every for required word. Below is the sample program to find the a given word Java in D:\test folder of files.

package in.javatutorials;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.regex.MatchResult;

/**
 * Search for the files in a folder and prints all file details.
 */
public class WordCrawlerInFolder {

private static String directoryPath = "D://test";
private static String searchWord = "Java";

public WordCrawlerInFolder() {
super();
}

public static void main(String[] args) {
   WordCrawlerInFolder crawler = new WordCrawlerInFolder();
    File directory = new File(directoryPath);

    if (directory == null || !directory.exists()) {
           System.out.println("Directory doesn't exists!!!");
           return;
    }
    crawler.directoryCrawler(directory, searchWord);
}

/**
* Gets all the file and directories and prints accordingly
* @param directory
* Directory path where it should search
*/
public void directoryCrawler(File directory, String searchWord) {

// Get List of files in folder and print
File[] filesAndDirs = directory.listFiles();

// Print the root directory name
//System.out.println("-" + directory.getName());

// Iterate the list of files, if it is identified as not a file call
// directoryCrawler method to list all the files in that directory.
for (File file : filesAndDirs) {

if (file.isFile()) {
searchWord(file, searchWord);
//System.out.println(" |-" + file.getName());
} else {
directoryCrawler(file, searchWord);
}
}
}

/**
* Search for word in a given file.
* @param file
* @param searchWord
*/
private void searchWord(File file, String searchWord){
Scanner scanFile;
try {
scanFile = new Scanner(file);
while (null != scanFile.findWithinHorizon("(?i)\b"+searchWord+"\b", 0)) {
MatchResult mr = scanFile.match();
System.out.printf("Word found : %s at index %d to %d.%n", mr.group(),
mr.start(), mr.end());
}
scanFile.close();
} catch (FileNotFoundException e) {
System.err.println("Search File Not Found !!!!! ");
e.printStackTrace();
}
}
}

We have used some escape characters in above class searchWord() method, below is the notation for the same.

  1. (?i) turn on the case-insensitive switch
  2. b means a word boundary
  3. java is the string searched for
  4. b a word boundary again.

If search term contain special characters, it would be suggested to use Q and E around the string, as it quotes all characters in between. Make sure the input doesn’t contain E itself.

Other Useful Links:

Javac/Java searching algorithm for other classes

Example program to reverse a Number in Java

How to find count of duplicates in a List

Threads Interview questions in Java

Like this post? Please share to your friends:
  • Finding a word in a document
  • Finding a word in a book
  • Finding a word from words game
  • Finding a word for the year
  • Finding a word by its definition