
Hi,
I need to write a java code for the following:
For example, if my file data.txt contains the following words: red green blue blue orange red green green
I should search for red, green, blue, orange as a predefined keyword in my code and my result should be in a EXCEL FILE as follows
Keyword Count red 2 green 3 blue 2 orange 1
Can anyone help me out with this?

Here is a code that reads the data from the text file, count the occurrence of each word and write the words and their occurrence into excel file. We have used POI api to write the data into excel file.
import java.io.*;
import java.util.*;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
public class CountWordOccurrence{
public static void main(String[] args){
try{
BufferedReader br=new BufferedReader(new FileReader("c:/data.txt"));
String str="";
String st;
while((st=br.readLine())!=null){
str+=st+" ";
}
HashMap<String, Integer> map = new HashMap<String, Integer>();
str = str.toLowerCase();
int count = -1;
for (int i = 0; i < str.length(); i++) {
if ((!Character.isLetter(str.charAt(i))) || (i + 1 == str.length())) {
if(i - count > 1) {
if (Character.isLetter(str.charAt(i)))
i++;
String word = str.substring(count + 1, i);
if (map.containsKey(word)) {
map.put(word, map.get(word) + 1);
}
else {
map.put(word, 1);
}
}
count = i;
}
}
ArrayList list1=new ArrayList();
ArrayList list2=new ArrayList();
ArrayList<Integer> list = new ArrayList<Integer>();
list.addAll(map.values());
Collections.sort(list);
int last = -1;
String filename="c:/count.xls" ;
HSSFWorkbook hwb=new HSSFWorkbook();
HSSFSheet sheet = hwb.createSheet("new sheet");
HSSFRow rowhead= sheet.createRow((short)0);
rowhead.createCell((short) 0).setCellValue("Keyword");
rowhead.createCell((short) 1).setCellValue("Count");
int k=1;
for (Integer i : list){
if(last == i)
continue;
last = i;
for(String s : map.keySet()){
if(map.get(s) == i) {
System.out.println(s + ":" + i);
list1.add(s);
list2.add(Integer.toString(i));
}
}
}
for(int i=0;i<list1.size();i++){
HSSFRow row= sheet.createRow((short)k);
row.createCell((short) 0).setCellValue(list1.get(i).toString());
row.createCell((short) 1).setCellValue(list2.get(i).toString());
k++;
}
FileOutputStream fileOut = new FileOutputStream(filename);
hwb.write(fileOut);
fileOut.close();
System.out.println("Your excel file has been generated!");
}
catch(Exception e){
System.out.println(e);
}
}
}

Thanks a lot! How ever can I ask a question? Is there a way to use tokenizer such as Scanner and get the output?
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.