Word count in text file

Hi,
I am trying to count word in my text file by using the Java code. Even though i am error in the code and don't know what sintaks to use. For example:
I have
school 4
bus 3
student 5
in a.txt
Another text file
bus 2
school 2
in b.txt
I want to display in new text file: c.txt
school 6 4 : a.txt 2 : b.txt
bus 5 3 : a.txt 2 : b.txt
student 5 5 : a.txt
Could you please advise,what sintak that i could use??
Thanks you..

Use StringTokenizer object and HashMap Object
example
String str = (your text readed from file A)
StringTokinzed token = new StringTokinzed(str);
while (token.hasMoreTokens()) {
String word = token.nextToken()
Integer i = (Integer) hashmap.get(word);
if (i==null) {
i = new Integer(1);
}else
i++;
hashmap.put(word,i);
same code for B file
iterate through the hasmap and print all word with the count

Similar Messages

  • Need help to add the words in a text file to an arraylist

    I am new to java and I really need some help for my project.I want to add the words of a text file to an arraylist. The text file consist of words and the following set of punctuation marks {, . ; : } and spaces.
    thanks in advance :-)

    I/O: [http://java.sun.com/docs/books/tutorial/essential/io/index.html]
    lists and other collections: [http://java.sun.com/docs/books/tutorial/collections/index.html]

  • To get  a  word in the text  file

    Hi,
    I m beginner to java.
    HOw i get a word in the text file.
    I used this code, it is only display the all sentence which are available in the text file.
    But , I need to print particular word (if it is available in that text file)
    package com.beryl;
    import java.io.*;
    class FileReadTest {
    public static void main (String[] args) {
         FileReadTest f = new FileReadTest();
    f.readMyFile();
    void readMyFile() {
         BufferedReader dis =null;
    String record = null;
    int recCount = 0;
    try {
    File f = new File("E:/hello/abc.txt");
    FileInputStream fis = new FileInputStream(f);
    BufferedInputStream bis = new BufferedInputStream(fis);
    dis
    = new BufferedReader(new InputStreamReader(bis));
    while ( (record=dis.readLine()) != null ) {
    recCount++;
    System.out.println(recCount + ": " + record);
    } catch (IOException e) {
    // catch io errors from FileInputStream or readLine()
    System.out.println("Uh oh, got an IOException error!" + e.getMessage());
    } finally {
    // if the file opened okay, make sure we close it
    if (dis != null) {
         try {
    dis.close();
         } catch (IOException ioe) {
    Thanks & Regards,
    kumar

    I used this code, it is only display the all
    sentence which are available in the text file.
    But , I need to print particular word (if it
    is available in that text file)if
    String.indexOf()

  • Reading words from a text file

    I have written code to store words in a text file. they appear in the text file as shown below.
    word1
    word2
    word3
    etc.
    I want to read each word individually and store them in an array. Im trying to do it using a BufferedReader but it doesn't seem to work. The code for reading the words is shown below. Any suggestions would be appreciated.
    try
    FileReader reader = new FileReader("words.txt");
    BufferedReader bReader = new BufferedReader(reader);
    ArrayList words = new ArrayList();
    String line;
    while((line = bReader.readLine()) != null)
    line = bReader.readLine();
    words.add(line);
    bReader.close();
    catch (Exception e)
    System.err.println ("Error writing to file");
    }

    I think your code is wrong, because it Read two time from file,
    your code like....
    while((line = bReader.readLine()) != null)
    line = bReader.readLine();
    words.add(line);
    you have to change the above code like
    while((line = bReader.readLine()) != null)
    words.add(line);
    NOW ITS WORKING FINE,...........

  • Replace/cut part of words from a text file.

    Hello Hello everyone, I have a quick question. I have my text file that contains also words like ... let's say abc1, abc2 and so on, and I need to cut the c from the word, I need ab1, ab2.
    Here is what I have started:
    import java.util.*;
    import java.io.*;
    public class test
            Vector<String> x = new Vector<String>();
    public mergefiles() throws IOException
            readAdd("test.txt");
            write("testout.txt");    
    private void readAdd(String name) throws IOException
            BufferedReader reader = new BufferedReader(new FileReader(name));
            String line,all=new String();
            while ((line = reader.readLine ()) != null)
                    all+=line+'\n';
            reader.close ();
            int posX=all.indexOf("X"); // x being like first word of the text file
              if (all.length()-posX>0)
                   String between=all.substring(posX+3,all.length());
                   StringTokenizer st=new StringTokenizer(between," \n");
    private void write(String name) throws IOException
            BufferedWriter writer = new BufferedWriter(new FileWriter(name));
            String s=new String();
             if (x.size()>0)
                  s+="X"+'\n';
             s+='\n';
             writer.write(s);
            writer.close();
    public static void main(String[] args) throws IOException
            new test();
    }I am new to Java and I would really appreciate if you would be patient with me.
    Thank you!

    I have tried in readAdd method something like:
    int posX=all.indexOf("X"); // x being like first word of the text file
              if (all.length()-posX>0)
                   string.replace("ab1","abc1");
              }     but still doesn't work, and this is not a really good ideea, in case that I have to replace 1000 of abci ...I should use a for in my write method:
    String[] s=new String[2];
    for(int i=0;i<word.length;i++)
                   BufferedWriter writer = new BufferedWriter(new FileWriter(testout.substring(0, testout.lastIndexOf("."))+(i+1)+".txt"));
                       writer.write(s);
              writer.close();
    But I not really sure if this is ok! Right now nothing is working
    Thanks                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Find words within a text file

    Hey all.
    I am playing around with the idea of finding a line of text within a text file, by using scanner and some next methods.
    The way I am trying to get it to work is that one enters a string and the program then finds all the lines of text containing that
    user-entered string and then prints them.
    The text file in question contains names of University papers and their room numbers, quantity of students etc.
    Example:
    IBUS212     EALT006     1am     72     AL     LI     
    BMSC241     MCLT102     2     pm     8     AL     COOREY     
    My problem annoyingly enough seems to be that I can't think how one could compare the string entered to the lines of text being
    scanned in the text file.
    My latest go involved what you see in the code, scanning the examdata.txt file for a user-entered course number, using course.next();
    by going with the example above it would be IBUS212. The task was to then to find all of the lines containing that number and print them out using
    println (what I have tried with id and line) as well as the rest of that line eg: EALT006     1am     72     AL     LI .
       public void printCourse()
        try
            String details, input, id, line;
            int count;
            Scanner user = new Scanner(System.in);
            System.out.println();
            System.out.println();
            System.out.println("Please enter your course ID: ");
            input = user.nextLine();
            Scanner course = new Scanner(new File("examdata.txt"));
            course.next();
            course.nextLine();
            id = course.next();
            line = course.nextLine();
            if(input.equals(id))
                System.out.println("Your course times are: "  + id + "and" + line);
            else
              System.out.println("Your course does not exist."); 
            catch(IOException e)
                System.out.print("File failure");
      }Any advice/help/troubleshooting would be greatly appreciated.
    Edited by: AUAN on Aug 13, 2009 9:43 AM
    Edited by: AUAN on Aug 13, 2009 9:44 AM
    Edited by: AUAN on Aug 13, 2009 9:49 AM

    You'll want [to loop while|http://java.sun.com/docs/books/tutorial/java/nutsandbolts/while.html] the course Scanner has a next line and then print the line if it contains the entered text.
    For useful methods you can check the Javadoc of String and Scanner (use your browser search on keywords like 'next' or 'contains' to find them).

  • Help!!! - Line Count in Text file

    I need to write a program for an assignment due next week. I should read between 30 and 70 lines of text from a text file. Each line contains an integral number of words. The program is required to display all the words on each line in revers order: "pass before they can enter" to read "enter can they before pass". I can reverse the words but the issue of 30 - 70 lines is a problem. I have the following code. What I'm I doing wrong???
    import java.io.*;
    import java.util.*;
    import java.util.StringTokenizer;
    public class LineReaderVector{
    public static void main(String args[])throws IOException{
    BufferedReader in=new BufferedReader(new FileReader("inpfile.txt"));
    LineNumberReader read=new LineNumberReader(new FileReader ("inpfile.txt"));
    String thisLine;
    int line=0;
    while((thisLine=in.readLine()) !=null){
         line=read.getLineNumber();
         StringTokenizer st = new StringTokenizer(thisLine);
         Vector v1=new Vector();
         while (st.hasMoreTokens()){
              String part= st.nextToken();
              v1.addElement(part);
         line++;
         System.out.println("\n");
         int size=v1.size()-1;
         for(int i=size; i>-1; i--){
         System.out.print(v1.elementAt(i).toString()+" ");
    }

    To read a file line by line this should do:
    try
      BufferedReader br = new BufferedReader(new FileReader("inpfile.txt"));
      String s = br.readLine();
      while (s != null)
        System.out.println(s);
        s = br.readLine();
      br.close();
    catch (IOException ex)
      ex.printStackTrace();
    ...

  • What is the best way of replacing words in a text file ?

    i want to read in a text file and when i come across a certain word, i want to change it to something else. Whats the best way to do this ?
    If i read in a line at a time, how would i only replace one word and not the rest of the line ?
    thanks

    thanks it works !!! But i wrote the contents to a new file.
    How do i overwrite the same file ? I put the the input and output file as the same location but it overwrites the original file with a blank one.
    i guess i have to write into another buffer and read all lines first before overwriting the file right ? how should i do that ?
    also, i only want to overwrite the file ONLY if applies replaceAll method, otherwise if no replacing takes place i dont want to keep updating the file everytime.

  • Cannot copy and paste text in word,excel or text file

    Cannot copy and paste in word,excel or in text file. It get paste in special charector.
    Eg. 
        ( )*  +    
        ( )*  +    

    Yesterday i update Yosemite and Adobe Photoshop CS6
    i found error text message like you everytime when i used fontAwesome on Adobe Photoshop CS6 and then i found out to fix this problems Yeahh…
    Try My Way to fix it out
    -> copy The Text you want to use
    -> paste your text (from your clipboard) To App TextEdit
    -> then Copy again
    -> back to Photoshop paste it on your document layout
    -> Done

  • 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

  • Putting words from a text file into a binary tree.

    I am having problems figuring out how to do this.
    the text file will have a sentence like this
    Every one likes to play games.
    My Dog tore up my apartment last night.
    How old are you sir.I know how to put regular strings into a binary tree, but I don't know what to do in order to put these textfile strings into it.
    I thought of using string tokenizer but I couldn't get that to work because the sentences are not a specific length, they can be any length. Can somebody give me some tips on what to use?
    Thank you

    JulianJ wrote:
    That will work?I'm sorry to tell you, that is a really bad question. Of course it won't work, because you did something else wrong. I have no idea what, but it's pretty certain that you haven't got everything right yet. (And that's nothing personal, it's just an observation about computer programming in general.) But don't let that stop you. And don't wait around for people to validate your ideas. Try it and see what happens. You won't break anything. And when it doesn't work, figure out why and carry on.

  • Replacing word in a text  file...in java

    hello;
    could anyone plz help me in writing a program in java that will replace a specific word with a specific word?Though i can read and write to a file. I need it urgently....plz help me...
    regards
    [email protected]

    public class wordReplace {
    public static void main(String [] args)
    String oldStr = "They can do it easily..." ;
    String newStr = oldStr.replaceAll("They", "You");
    System.out.println(newStr);
    }

  • Does java print service support word docs or text files

    Can anyone tell me that java print service api allows to print word doc files or RTF files etc.

    no it doesn't.
    To print a Word Doc you need to be able to read it, and display it.
    Anything that can be displayed in, say a JPanel, can be printed, cos it's just a matter of displaying the
    image to a virtual component ( a print canvas ). Which then gets printed.
    So, because Java doesn't immediately support Ms Docs, neither does the print service.
    regards,
    Owen

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

Maybe you are looking for

  • Error updating two reports on same page! Could you have a look please?

    Hey guys! I have the following situation : two updateable reports on one page with IDs 'DATE_REPORT' and 'WORK_REPORT' two pl/sql processes on submit after c.... named 'SUBMIT_DATE' and 'SUBMIT_WORK' two buttons named 'SAVE_DATE' and 'SAVE_WORK' Fina

  • Transformation   XSLT

    Hi,   Im new to XSLT.   I have to create an abap program using transformation to dymanically put data into Excel using XSLT . Plz let me know with an example. also is it possible to save an excel file directly as XSLT? Regards, Vimal

  • How to setup singnet email using other? So desperate.

    Can anyone in Singapore help me. I bought it from shop. How to setup singnet email under add new account> other>......

  • Installing CS5 on iMac, already using on Mac Book Pro, originally installed on Mac Book.

    I originally installed the software on Mac Book but removed it when I passed along that computer to my partner. I installed on MB Pro with no problem. Now cannot install on new iMac. Cannot deactivate on Mac Book because there is no Adobe software on

  • Is there a "Task Manager" for HyperV Guests?

    I have read articles such as http://msdn.microsoft.com/en-us/library/cc768535(v=bts.10).aspx that indicate which performance counters to watch in the Guest.  An article is fine but the day-to-day network Admin needs better than that. They need a tool