Thursday 21 January 2016

Java program to count occurrence of each word in a file

Question:


Write a program to display frequency count of each word in a file. Filename will be provided by user.

Desired Output:

Enterfilname: 
A.txt

the 2
is 3..

Source code: 


import java.io.*;
import java.util.*;
class AB
{
public static void main(String args[]) throws IOException
{
//Entering file name
System.out.println("Enter File name along with path: ");
Console con=System.console();

//getting all unique tokens
StreamTokenizer st=new StreamTokenizer(new FileInputStream(con.readLine()));
HashSet set=new HashSet();
while(st.nextToken() != StreamTokenizer.TT_EOF)
{
switch(st.ttype)
{
case StreamTokenizer.TT_WORD:
set.add(st.sval+"");
break;
case StreamTokenizer.TT_NUMBER:
set.add(st.nval+"");
break;
}
}

//searching for number of time each token occured
HashMap map=new HashMap();
Iterator itr=set.iterator();
while(itr.hasNext())
{
String s=(String)itr.next();
int counter=0;
StreamTokenizer st1=new StreamTokenizer(new FileInputStream("abc.txt"));
while(st1.nextToken() != StreamTokenizer.TT_EOF)
{
if(s.equals(st1.sval) || s.equals(st1.nval+"")) counter++;

}
map.put(s,counter);
}

//printing output
Set set1=map.keySet();
itr=set1.iterator();
while(itr.hasNext())
{
String s1=(String)itr.next();
System.out.println(s1+"\t"+map.get(s1));
}
}
}

1 comment: