Search word in text file

Hello,
someone can help me with code?
How to search in text file any word and count how many it were repeated?
For example test.txt:
hi
hola
hey
hi
bye
hoola
hiAnd if I want to know how many times are repeated in test.txt word "Hi" program must say "3 times repeated"
I hope you understood what I want, thank you for answers.

This is my code now.
package lt.kvk.i3_2.test;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class Testing {
          public static void main(String args[]) throws Exception {
               Scanner input = new Scanner(System.in);
            System.out.println("Select word from list:");
            System.out.println();
            try {
                    FileReader fr = new FileReader("src/lt/kvk/i3_2/test/List.txt"); // this is list of words, everything all right here
                    BufferedReader br = new BufferedReader(fr);
                    String s;
                    while((s = br.readLine()) != null) {
                         System.out.println(s);
                    fr.close();
                    String stilius = input.nextLine();   // eneter word which I want to count in File.txt
                BufferedReader bf = new BufferedReader(new FileReader("src/lt/kvk/i3_2/test/File.txt")); // from this file I need to count word which I entered before
                int counter = 0;               
                counter = counter + 1;
                counter++;
                counter += 1;
                String line;
                System.out.println("Looking for information");
                while (( line = bf.readLine()) != null){
                int indexfound = line.indexOf(stilius);
                if (indexfound > -1) {
                System.out.println( "At all words which You want to count are "+ counter);
                bf.close();
            catch (IOException e) {
                System.out.println("Error");
          }         Here example of file.txt:
test
tea
tree
test
car
wind
dog
test
car
sea
tea
testIf I enter for example word "test" or any from this list I got answer:
Looking for information
At all words which You want to count are 3But it must to count how many times in this file this word are repeated, it must be 4
if I enter word car It must show 2....
And if I enter word which isn't in list (file.txt)
Program didn't show error, just:
Looking for informationThanks for answers.

Similar Messages

  • Find exact word in text file tht is present in an excel sheet

    Hi all,
    i want to find words in an text file.
    but the criteria is i want to search words which r already listed in another excel sheet and change the color of these word.
    i used FileInputStream
    and also BufferedInputStream
    cany anyone help me with this

    hi kajbj,
    can u plz tell me how to do in VBA then
    will find out the way to do in java
    Thanx

  • Seachring word from text file

    Hi...There..
    I h'va wrirtten Search application which search words from Simple text files.
    My file contains list of words separated by "\n"(new line).
    i am using java.io.BufferedReader for reading file.
    i'want to search word from file within few milliseconds, but when my file containo more then some 2lake words(200000) my process of readind comsumes more then 5 sec. time to search.
    pl. suggest me effective method to search word from file so i can make it rapid search.
    Actually i 've to provide search on "TEXT VALUE CHANGED EVENT" so even if my process takes more then one seconds it is not physible for me.
    Thanks in Advance.
    Timir Patel.

    Try this:
    import java.io.*;
    import java.util.*;
    public class searcher
              private static long [] indexes;
         private static class temp_data
              public final String text;
              public final long starts_at;
              public temp_data(String t, long l)
                   text = t;
                   starts_at = l;
         private static class temp_cmp implements Comparator
              public int compare(Object o1,Object o2)
                   return ((temp_data)o1).text.compareTo(
                             ((temp_data)o2).text);
         /** creats index table. You should do it once, and rather store index
         table in file then. This method has high peak memory usage but it is
           easy to optimize it.*/
         private static void buildIndex(RandomAccessFile file)throws Exception
              List temp = new LinkedList();
              String st;
              long p = file.getFilePointer();
              while((st = file.readLine())!=null)
                   temp.add(
                        new temp_data(st,p)
                   p = file.getFilePointer();
              Collections.sort(temp,new temp_cmp());
              indexes = new long[temp.size()];
              int i=0;
              for(Iterator I=temp.iterator();I.hasNext();i++)
              temp_data tt = ((temp_data)I.next());
               System.out.println("indexing :"+tt.text+" ["+tt.starts_at+"]");
                   indexes=tt.starts_at;
         /** returns position at which text starts or -1 if not found */
         public static long find(String text,RandomAccessFile file)throws Exception
              int ncp = indexes.length/2;
              int n = 2;
              int cp;
              do{
              cp = ncp;
                   file.seek(indexes[cp]);
                   String tt = file.readLine();
              System.out.println("comparing with "+tt);
                   int cmpr = text.compareTo(tt);
                   if (cmpr==0)
                        return indexes[cp];
                   else
                   if (cmpr>0)
                        ncp = cp+(indexes.length / (1<<n));
                   else
                        ncp = cp-(indexes.length / (1<<n));
                   n++;
              }while(ncp!=cp);
              return -1;
         public static void main(String args [] )throws Exception
              RandomAccessFile f = new RandomAccessFile(args[0],"r");
              buildIndex(f);
              for(int i=1;i<args.length;i++)
              System.out.println("searching for \""+args[i]+"\"");
              System.out.println("found at:"+find(args[i],f));
              f.close();
    It should work, however I gave it less than five minutes testing.

  • Read a non english word from text file

    While Reading thai charater from text file which was sent by QAD(a different application),
    We are reading 60 char using substr() function.
    If the data is English word it reads correctly with 60 char.
    But if it is in thai characters it returns more than 60 char.
    In oracle all NLS Char set has been already set.
    Can anyone help in this issue
    thanks in advance

    Maybe you should use SUBSTRC, SUBSTR2 or SUBSTR4 depending on the character set of your database. See http://download-uk.oracle.com/docs/cd/B10501_01/server.920/a96540/functions119a.htm#87068
    Message was edited by:
    Pierre Forstmann

  • Write diadem search results to text file

    Is there a solution within DIAdem for exporting specific information from a search result into a text file? For example: I perform a search which returns all of the files, groups, and/or channels which I want to work with; now I would like to have, say, the file paths of all the results of my search exported to a text file. Is this possible? I could not find a direct way of doing this, but perhaps a script already exists for doing stuff like this?

    Hi mrclary,
    I did not have this code handy, but I was able to whip it up for you.  Let me know if you have any questions.
    Brad Turpin
    DIAdem Product Support Engineer
    National Instruments
    Attachments:
    Search Result Paths.zip ‏1 KB

  • How to highlight searched words in pdf file opens from web??

    Hello fellows
    I need to create a web page that holds couple controls include "search" button .When client clicks on the button the programm will search pdf file, open it in client reader with highlight on searched words ..
    Is that any posibility to do it using javascript on a client or c# ,vb.net on the server ??
    I'm very novice in PDF developing so any ideas or conclusions would be very usefull!

    Thank you for answer
    But maybe you have any idea how I can do it??
    This is very important feature for our project.
    Some additional information : our project will hosted in SharePoint 2007
    When I use adobe Ifilter for moss and set in querystring #search="searchword"  I get highlights, but only in a browser.
    But if a reader was configured to open client application this feature wasn't work.
    Any suggestion ???

  • Reading first word from text file

    Hello all,
    I created a program which I can type in a line and store it into a file. What I need my next program to do is read and display just the first word from each line on the text file.
    Here is what I have:
    import java.io.*;
    public class ReadFromFile
    public static void main (String args[])
         FileInputStream firstWord;          
              try
                  // Open an input stream
                  firstWord = new FileInputStream ("FileofWords.txt");
                  // Read a line of text
                  System.out.println( new DataInputStream(firstWord).readLine() );
                  // Close our input stream
                  firstWord.close();          
                   System.err.println ("Unable to read from file");
                   System.exit(-1);
    }

    what i would like is my program to get the first word of every line and put it in my array.
    This is what i have attempted.
    import java.io.*;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.BufferedReader;
    public class testing {
         String[] tmp = new String [2];
         String str;
         public void programTest()
              try
                             BufferedReader in2 = new BufferedReader(new FileReader("eventLog.log"));
                             while ((str = in2.readLine()) != null)
                                  tmp = str.split(" ");
                                  System.out.println(tmp[0]);
                        catch(IOException e)
                             System.out.println("cannot read file");
    public static void main(String[] args)
                 testing B = new testing();
                 B.programTest();
    }//end classAny help is most appreciated

  • Searching for a text file

    hi i want to search for a file in the same folder as my project and read the contents of that file ... i know how to read from text file but i just need to know how i can search in the folder to look for a txt file called me.txt and open it for reading.. any suggestions?
    thanks in advance
    please provide some code for me... thx alot

    Look at the File class in Java API. You can create a file object by passing the file name.
    Then you can check whether the file exists or not by using exist methos of the File. (Of course, you need to know the path of the file).

  • Binary search in a text file.

    Is it possible to carry out binary search directly in the text file without passing the file data into a List data, in order to save RAM?

    If the file is sorted, and if you know what byte position each record begins at, then, yes, using RandomAccessFile you can do this.
    I don't know if it's really the best approach though. If the file's not all that big, or if the relevant parts of its content can be represented in more compact form, then sorting in memory will be simpler and quicker.

  • Need to search contents of text files on a windows network drive....

    I am trying to search the content of a directory on a windows network drive for that contains .sas files (essentially text files) for a certain text string. Find does not seem to do this. Any ideas/suggestions?
    When I copy a file to my desktop I can do it easily, but that is not an option.

    Uh yeah....in my opinion GREATLY affects Apple's claim to windows compatibility......unless there is a solution out there. My firm is windows-based and we have a terabyte or so of data and files related to various stuff all buried in subfolders..and all I want is to search one folder for one text string.
    I'm praying for a solution here.....

  • Find word in text file and count specific words

    now I'll try to explain what I need to do. I have file.txt file, It looks like:
    John //first line - name
    One
    Three
    Four
    Peter //first line - name
    Two
    Three
    Elisa //first line - name
    One
    Three
    Albert //first line - name
    One
    Three
    Four
    Nicole //first line - name
    Two
    FourSo I have program's code:
    public class Testing {
            public static void main(String args[]) throws Exception {
                Scanner input = new Scanner(System.in);
                System.out.println("Select word from list:");
                System.out.println();
                try {
                    FileReader fr = new FileReader("src/lt/kvk/i3_2/test/List.txt"); // this is list of words, everything all right here
                    BufferedReader br = new BufferedReader(fr);
                    String s;
                    while((s = br.readLine()) != null) {
                        System.out.println(s);
                    fr.close();
                    String stilius = input.nextLine();   // eneter word which I want to count in File.txt
                    BufferedReader bf = new BufferedReader(new FileReader("src/lt/kvk/i3_2/test/File.txt")); // from this file I need to count word which I entered before
                    int counter = 0;               
                    String line;
                    System.out.println("Looking for information");
                    while (( line = bf.readLine()) != null){
                        int indexfound = line.indexOf(stilius);
                        if (indexfound > -1) {
                             counter++;
                    if (counter > 0) {
                        System.out.println("Word are repeated "+ counter + "times");}
                        else {
                        System.out.println("Error...");
                    bf.close();
                catch (IOException e) {
                    System.out.println("Error:" + e.toString());
            }This program counting specific word (entered by keyboard) in file.txt.
    I need to make this program: for ex.: if I enter word: One It must show:
    Word One repeated 3 times by John, Elisa, AlbertAll what I need to elect by who this word repeated. But I don't know really how to make It, maybe LinkedList or I dont know, someone could help me?
    Thank you very much.

    966676 wrote:
    All what I need to elect by who this word repeated. But I don't know really how to make It, maybe LinkedListYou should choose the simplest type fullfilling your needs. In this case I'd go for <tt>HashSet</tt> or <tt>ArrayList</tt>.
    or I dont know, someone could help me?You need to introduce a variable to store the actual name which must be resetted if an empty line is found and then gets assigned the verry next word in the file.
    bye
    TPD

  • Read words from text file by delimiter as columns and rows

    Hi All,
    I need your help as i have a problem with reading string by delimiter. i have used various tech in java, but i can not get the result as expected.
    Please help me to get the string from text file and write into excel . i have used a text file.
    problem
    get the below as string by delimiter
    OI.ID||'|'||OI.IDSIEBEL||'|'||OI.IDTGU||'|'||OI.WORKTYPE||'|'||OI.UTR_FK
    read the below as string by delimiter
    "50381|TEST_7.15.2.2|09913043548|Attivazione|07-SEP-10
    now i need to write the above into excel file as columns and rows.
    there are 5 columns and each corresponding values
    the outut excel should be
    OI.ID OI.IDSIEBEL OI.IDSIEBEL OI.WORKTYPE OI.UTR_FK
    50381 TEST_7.15.2.2 09913043548 Attivazione 07-SEP-10
    i tried in diffrerent techinq but not able to get the resule. pls help me
    Thanks,
    Jasmin
    Edited by: user13836688 on Jan 22, 2011 8:13 PM

    First of all, when posting code, put it between two tags.
    Second of all, the pipe is a special character in regex, so you need to escape it as
    .split("\ \|");
    Erh. So 2 backslashes before the pipe character. Stupid forum won't post it.
    Edited by: Kayaman on Jan 24, 2011 9:35 AM
    Edited by: Kayaman on Jan 24, 2011 9:35 AM
    Edited by: Kayaman on Jan 24, 2011 9:36 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Binary search in text files

    Hi all,
    I'm thinking about how to implement a binary sort to get,given a key, a value from a text file with a list of words in order. I saw randomaccessfile for j2se and I know that this work it's usually done by seek functions but how to do the seek work without the File class , with only the InputStream and Reader? I'm talking about the j2me midp 2 cldc 1.1 api, is there some methods or class to use for this thing? How could be implemented a binary search in a text file resident in the /res dir or the JAR or which could be the problems that cannot make possible this staff? If there was something like seek one way could be that one of decide a common length of words to read so going to the half of the text file it's possible with simply multiplication, and the do the binary search things.But for now I haven't found any resources or help.
    I hope you can help me to understand, thank you

    Hallo all,
    it is NOT the problem to locate the text I need to find in the fmb, or fmx.
    The problem is that since I want to change not only the text but also some more code around I want to do this in Form Builder - Object Navigator. And I'm not able to discover in which trigger or procedure the text appears.
    I do not want to edit fmx, or fmb in a text editor because I suupose theer are some checksums hidden for the format.
    -duro
    BTW in FMT there is no code seen (only some binary) for v6i as it was in v4.5.

  • Read words from a text file into an undefined array

    Dear all,
    Does anyone know how to read words in text file, seperated by all types of spaces ("_", "\n", "\t","\r","\f") and put them into a string array to be used later?
    So far I can read the words using the Tokenizer but can't assign to array:
    public class reader
    StringTokenizer tokenizer = new StringTokenizer(input);
    String[ ] array= null;  //unknown size of array
    int i=0;
                   while(tokenizer.hasMoreTokens())
                             array[i] = tokenizer.nextToken();
                             i++;
    Any suggestions welcome!
    thanks in advance!

    Hi
    sorry wrote in a hurry ;) din c the problem clearly
    there are two approaches
    1) best approach for your problem is Vector or ArrayList, these would make life easy for you.
    Always collections are better approach over arrays when the size is dynamic. However in your case the size cant be said to be DYNAMIC. coz the number of words will not grow / shrink during the runtime.. i know that number of words are not fixed but dynamic is something which will grow/shrink during runtime. but still collection is better approach.
    2)dirty approach
    use double dimensional array
    String arr[][] = null;
    then use one tokenizer for StringTokenizer(str,"\n");
    using countTokens on this will give you number of lines.
    use this to initialize array
    arr = new String[lineCount][];
    then iterate from 1 to lineCount and use 1 more tokenizer to get number of words for that line. use this number to initialize the column size for arr[i] like
    arr[i] = new String[wordCount];
    then store the token using nested for loops in this array
    go for the 1st one ;) 2nd one is hedious n time consuming but both will work ;)
    cheers
    amey

  • Extract text file from a folder and read the content

    Hi
    I have "n" no.of text files saved in a folder with automatically generated naming convention which include DD/MM/YYYY and also some measurement output value.
    Eg: 1) Die_1_DUT_outputvalue_DD_MM_YYYY.txt
        2) Die_1_DUT_outputvalue_DD_MM_YYYY_ABC.txt
    In the above files part of the 2nd file naming convention same as the first file (i.e. Die_1_DUT and DD_MM_YYYY) whereas outputvalue is different and an additional string named ABC is appended.
    Now I want to search the 2nd file based on matching the naming pattern with the 1st file (note: the outputvalue in the file name is different for both files) and so far followed this method
    1) Use a list folder with *.txt pattern to search all the text files and the output is a 1D array
    2) then use array to cluster and then flatten to XML function to have all the text file names as a string element (not 1D array)
    3) then pass the output of the 2nd step to the sting match pattern and use a regular expression to get the required file name
    4) send the output of the 3rd step to search 1D array to get the index and then get the file name and later use read text file to read the content of the text file
    And I am stuck at the 3rd step while sending an input as the regular expression to match the pattern as the outputvalue in the namming convention of the above two files is different is there any way I can actually extract the filename/file?
    Any suggestions?
    Attachments:
    1.png ‏11 KB

    Some bits in your code are unnecessary, a leaner implementation here:
    Beginner? Try LabVIEW Basics
    Sharing bits of code? Try Snippets or LAVA Code Capture Tool
    Have you tried Quick Drop?, Visit QD Community.

Maybe you are looking for

  • Getting files from a hard drive used w/mac = PC

    Hey all, I have an external hard drive that was used with a mac. There are a bunch of files that I need off the hard drive, but every time I plug the hard drive into the pc, the computer knows it's there but I can't access any of the info on the driv

  • Bridge opens JPEG files in Windows Photo Viewer not Photoshop

    How do I tell Bridge to open my JPEG files in Photoshop and not Windows Photo Viewer? I see that Windows Photo Viewer is selected as the default in my preferences and I do not see Photoshop as an option. I do see COM Surrogate 6.1. I just upgraded fr

  • Standard SMARTFORM  for Check Printing/ Payment Advice

    Hi All,   I have one important question... Standard <b>Script</b> Check Print Program =  <b>RFFOUS_C</b> Standart Script Layout Name  = F110_PRENUM_CHCK                             &  F110_D_AVIS We have to modify it as per client requirment.     But

  • Configuration information

    Hi, We are going to use AT-MIO-16E-10 and PCI-DIO-32SH in RTX subsystem, a real-time extention for Windows NT. I need detail information about the port addresses for all analog and digital I/O for development of device drivers in RTX. Does anyone kno

  • Anyone managed to change SBS2011 RWW to allow UPN username?

    Per the subject, in SBS2011 you can use a UPN logon for OWA but not for RWW. Was wondering if anyone had ever changed the logon page to allow this?