Как найти слово в файле java

let’s say I have a txt file containing:

john
dani
zack

the user will input a string, for example “omar”
I want the program to search that txt file for the String “omar”, if it doesn’t exist, simply display “doesn’t exist”.

I tried the function String.endsWith() or String.startsWith(), but that of course displays “doesn’t exist” 3 times.

I started java only 3 weeks ago, so I am a total newbie…please bear with me.
thank you.

asked Dec 6, 2013 at 7:21

user3040333's user avatar

Just read this text file and put each word in to a List and you can check whether that List contains your word.

You can use Scanner scanner=new Scanner("FileNameWithPath"); to read file and you can try following to add words to List.

 List<String> list=new ArrayList<>();
 while(scanner.hasNextLine()){
     list.add(scanner.nextLine()); 

 }

Then check your word is there or not

if(list.contains("yourWord")){

  // found.
}else{
 // not found
}

BTW you can search directly in file too.

while(scanner.hasNextLine()){
     if("yourWord".equals(scanner.nextLine().trim())){
        // found
        break;
      }else{
       // not found

      }

 }

answered Dec 6, 2013 at 7:22

Ruchira Gayan Ranaweera's user avatar

7

use String.contains(your search String) instead of String.endsWith() or String.startsWith()

eg

 str.contains("omar"); 

answered Dec 6, 2013 at 7:22

Prabhakaran Ramaswamy's user avatar

You can go other way around. Instead of printing ‘does not exist’, print ‘exists’ if match is found while traversing the file and break; If entire file is traversed and no match was found, only then go ahead and display ‘does not exist’.

Also, use String.contains() in place of str.startsWith() or str.endsWith(). Contains check will search for a match in the entire string and not just at the start or end.

Hope it makes sense.

answered Dec 6, 2013 at 7:24

Ankur Shanbhag's user avatar

Ankur ShanbhagAnkur Shanbhag

7,7062 gold badges28 silver badges38 bronze badges

0

Read the content of the text file: http://www.javapractices.com/topic/TopicAction.do?Id=42

And after that just use the textData.contains(user_input); method, where textData is the data read from the file, and the user_input is the string that is searched by the user

UPDATE

public static StringBuilder readFile(String path) 
 {       
        // Assumes that a file article.rss is available on the SD card
        File file = new File(path);
        StringBuilder builder = new StringBuilder();
        if (!file.exists()) {
            throw new RuntimeException("File not found");
        }
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

       return builder;
    }

This method returns the StringBuilder created from the data you have read from the text file given as parameter.

You can see if the user input string is in the file like this:

int index = readFile(filePath).indexOf(user_input);
        if ( index > -1 )
            System.out.println("exists");

answered Dec 6, 2013 at 7:25

Hitman's user avatar

HitmanHitman

5884 silver badges10 bronze badges

1

You can do this with Files.lines:

try(Stream<String> lines = Files.lines(Paths.get("...")) ) {
    if(lines.anyMatch("omar"::equals)) {
  //or lines.anyMatch(l -> l.contains("omar"))
        System.out.println("found");
    } else {
        System.out.println("not found");
    }
}

Note that it uses the UTF-8 charset to read the file, if that’s not what you want you can pass your charset as the second argument to Files.lines.

answered Sep 19, 2018 at 6:40

Alex - GlassEditor.com's user avatar

how to search for a certain word in a text file in java?
Using buffered reader, I have this code, but I get a

java.lang.ArrayIndexOutOfBoundsException

Please help me determine what’s wrong with my program.

System.out.println("Input name: ");
      String tmp_name=input.nextLine();


        try{

             FileReader fr;
      fr = new FileReader (new File("F:\names.txt"));
      BufferedReader br = new BufferedReader (fr);
String s;
while ((s = br.readLine()) != null) {

String[] st = s.split(" ");
String idfromtextfile=st[0];
String nemfromtextfile = st[1];
String scorefromtextfile=st[2];


if(nemfromtextfile.equals(tmp_name)){
    System.out.println("found");      
}else{
    System.out.println("not found");
}



      }

  }catch(Exception e){ System.out.println(e);}

names.txt looks like this:

1
a
0

2
b
0

asked Oct 6, 2010 at 8:05

user225269's user avatar

user225269user225269

10.6k69 gold badges173 silver badges250 bronze badges

1

Your code expects each line in the file to have three space-separated words. So your file must look like this:

1 a 0
2 b 0

The ArrayIndexOutOfBoundsException occurs if there is a line in the file that does not have three space-separated words. For example, there might be an empty line in your file.

You could check this in your code like this:

if ( st.length != 3) {
    System.err.println("The line "" + s + "" does not have three space-separated words.");
}

answered Oct 6, 2010 at 9:02

fstab's user avatar

fstabfstab

9921 gold badge11 silver badges19 bronze badges

You can use the Pattern/Matcher combination described here, or try the Scanner. Use the Buffered reader like this :

BufferedReader in
   = new BufferedReader(new FileReader("foo.in"));

and extract the string with in.toString()

Sean Patrick Floyd's user avatar

answered Oct 6, 2010 at 8:08

kostja's user avatar

kostjakostja

60.1k48 gold badges178 silver badges224 bronze badges

If text is huge and you don’t want to read it at once and keep in memory. You may constantly read a line with readLine(), and search each of the output line for a pattern.

answered Oct 6, 2010 at 8:21

Gadolin's user avatar

GadolinGadolin

2,6263 gold badges26 silver badges33 bronze badges

Here is an example of how to do it using BufferedReader
link text

answered Oct 6, 2010 at 8:27

Suresh Kumar's user avatar

Suresh KumarSuresh Kumar

11.1k9 gold badges44 silver badges54 bronze badges

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';
    }
}

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

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

Добавить комментарий