Find word 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

Fast comes at a price…. code complexity and perhaps readability.

Assuming that your code produces the right results now…. and it is a big assumption because:

  • it expects the word to be at the beginning/end of the line, or surrounded by spaces (not commas, punctuation, etc.)
  • it does not look for the word inside another string, it will match ‘are’, but not ‘bare’.

OK, a much faster way (keeping it as Java), is to do the following:

  1. Convert the search string (‘are’) to a byte-array in the same encoding as the file.
  2. Open a memory-mapped byte-buffer from a File-Channel on the file.
  3. Scan the ByteBuffer, looking for matches to the search byte-array
  4. count the newlines as you go.
  5. close the ByteBuffer

If the file is larger than your memory, you will have to re-position the byte-buffer occasionally. I recommend using a emopry-mapped size of about 4MB plus the size of the search-string. That way you can search the 4MB window, and then start the next window at the next 4mb boundary.

Once you get in to it, it will make sense.

This system will be fast because you will never have to copy the file’s data in to Java. Everything will actually happen in the native side of things.

There is a lot to read to make it work.

I would start with a tutorial….

  • StudyTrails
  • Yaldix
  • LinuxTopia

of course, if you want really fast, use grep.

Here is some example code that may get you started:

import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;


public class NIOGrep {

    public static void main(String[] args) throws IOException {
        if (args.length != 2) {
            throw new IllegalArgumentException();
        }
        String grepfor = args[0];
        Path path = Paths.get(args[1]);

        String report = searchFor(grepfor, path);

        System.out.println(report);

    }

    private static final int MAPSIZE = 4 * 1024 ; // 4K - make this * 1024 to 4MB in a real system.

    private static String searchFor(String grepfor, Path path) throws IOException {
        final byte[] tosearch = grepfor.getBytes(StandardCharsets.UTF_8);
        StringBuilder report = new StringBuilder();
        int padding = 1; // need to scan 1 character ahead in case it is a word boundary.
        int linecount = 0;
        int matches = 0;
        boolean inword = false;
        boolean scantolineend = false;
        try (FileChannel channel = FileChannel.open(path, StandardOpenOption.READ)) {
            final long length = channel.size();
            int pos = 0;
            while (pos < length) {
                long remaining = length - pos;
                // int conversion is safe because of a safe MAPSIZE.. Assume a reaosnably sized tosearch.
                int trymap = MAPSIZE + tosearch.length + padding;
                int tomap = (int)Math.min(trymap, remaining);
                // different limits depending on whether we are the last mapped segment.
                int limit = trymap == tomap ? MAPSIZE : (tomap - tosearch.length);
                MappedByteBuffer buffer = channel.map(MapMode.READ_ONLY, pos, tomap);
                System.out.println("Mapped from " + pos + " for " + tomap);
                pos += (trymap == tomap) ? MAPSIZE : tomap;
                for (int i = 0; i < limit; i++) {
                    final byte b = buffer.get(i);
                    if (scantolineend) {
                        if (b == 'n') {
                            scantolineend = false;
                            inword = false;
                            linecount ++;
                        }
                    } else if (b == 'n') {
                        linecount++;
                        inword = false;
                    } else if (b == 'r' || b == ' ') {
                        inword = false;
                    } else if (!inword) {
                        if (wordMatch(buffer, i, tomap, tosearch)) {
                            matches++;
                            i += tosearch.length - 1;
                            if (report.length() > 0) {
                                report.append(", ");
                            }
                            report.append(linecount);
                            scantolineend = true;
                        } else {
                            inword = true;
                        }
                    }
                }
            }
        }
        return "Times found at--" + matches + "nWord found at--" + report;
    }

    private static boolean wordMatch(MappedByteBuffer buffer, int pos, int tomap, byte[] tosearch) {
        //assume at valid word start.
        for (int i = 0; i < tosearch.length; i++) {
            if (tosearch[i] != buffer.get(pos + i)) {
                return false;
            }
        }
        byte nxt = (pos + tosearch.length) == tomap ? (byte)' ' : buffer.get(pos + tosearch.length); 
        return nxt == ' ' || nxt == 'n' || nxt == 'r';
    }
}

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.

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

Like this post? Please share to your friends:
  • Find word ending with
  • Find word document on this computer
  • Find word document by text
  • Find word definitions online
  • Find word definitions dictionary