Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Answers Viewqa Java-Beginners Writing a code for Scanning a text file in local drive for a predefined keyword and counting the number of occurance of that keyword in that text file and exporting the output into an excel file.

Have Programming Question? Ask it here!
 
 
 


vishnu radhan
Writing a code for Scanning a text file in local drive for a predefined keyword and counting the number of occurance of that keyword in that text file and exporting the output into an excel file.
2 Answer(s)      a year and 9 months ago
Posted in : Java Beginners


Hi,

I need to write a java code for the following:

  1. Scanning a local .txt file for a predefined keyword.
  2. Counting the number of occurances for that keyword.
  3. Exporting the result to a excel file

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?


Advertisement
View Answers

November 26, 2012 at 5:05 PM


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


November 27, 2012 at 12:18 PM


Thanks a lot! How ever can I ask a question? Is there a way to use tokenizer such as Scanner and get the output?



Related Tutorials/Questions & Answers:
writing a text into text file at particular line number
writing a text into text file at particular line number   Hi, thanks for quick response, I want to insert text at some particular line number.. after line number four my text will display in text file using java program
writing a text into text file at particular line number
writing a text into text file at particular line number   Hi, thanks for quick response, I want to insert text at some particular line number.. after line number four my text will display in text file using java program  
Advertisements
writing a text into text file at particular line number
writing a text into text file at particular line number   Hi, thanks for quick response, I want to insert text at some particular line number.. after line number four my text will display in text file using java program  
counting the values in input file and and writing the output to a file
counting the values in input file and and writing the output to a file  Can any one please correct this code. This is to read a file and later...-code/16483-counting-values-input-file-writing-output-file.html this code
write a program in java to read a text file and write the output to an excel file using filereader and filewriter?
write a program in java to read a text file and write the output to an excel file using filereader and filewriter?  write a program in java to read a text file and write the output to an excel file using filereader and filewriter
a jsp code for creating a text file
a jsp code for creating a text file  Hello,i need jsp code for creating a new text file for each user, when they login in to the website for creating a new data file. So i need a jsp code for following options. when user login
text file
text file  Hello can I modify the program below so that all the numerical data is stored in an external text file,that is the data contained... java.util.Scanner; class HardwareItems { String code; String description; double
text file
text file  Hi can you help me I have to modify the program below so that all the data held in it is stored in an external text file.So there should... at the start of the program from a seperate external text file.Thank you! mport
Reading a text file in java
Reading a text file in java  What is the code for Reading a text file... in java.io.* package for reading and writing to a file in Java. To learn more about reading text file in Java see the tutorial Read File in Java. Thanks
Sorting text file
Sorting text file  Hello friends, i'm writing search page for my local website. i'm storing all file list in text file. And also adding a value... according to begin value. Text File having list like this: 5| 3| can anyone
Java Read Lines from Text File and Output in Reverse order to a Different Text File
Java Read Lines from Text File and Output in Reverse order to a Different Text... to another text file. When that is done the output values of that file need... by line and output in reverse order to the text area field. Can someone help
Convert Text File to PDF file
Convert Text File to PDF file  Here is the way how to covert your Text file to PDF File, public class TextFileToPDF { private static void...(document, new FileOutputStream( "**OUTPUT FILE
how to seach a keyword in a xml file - XML
how to seach a keyword in a xml file  i have a xml file. i wanted to read and store all the tag values. i have a html form in which when i enter some keyword say "a" then it has to display the tag values starting with a letter
Convert Text File to PDF file
Convert Text File to PDF file  import java.io.BufferedReader; import... FileOutputStream( output file)); document.open(); document.add...); System.out.println("Text is inserted into pdf file"); document.close
Map words to line number in text file and show occurence
Map words to line number in text file and show occurence  hi i want to Map words to line number in text file and show occurrence of word in java coding
upload a file into database and progrm should support excel and text and csv file formats
upload a file into database and progrm should support excel and text and csv file formats  Hai all, I need a program to upload a file into database table... and the program should support .excel ,.txt ,.csv file formats. can
Problem while using a HashMap for writing text ina RTF file. - Framework
Problem while using a HashMap for writing text ina RTF file.  Hi, I am trying to generate a RTF file using iText.jar, wherein I am taking... matched to the string then only write to the RTF file. Problem is Document writes
how to update the text file?
how to update the text file?  if my text file contains a string and integer in each line say,: aaa 200 bbb 500 ccc 400 i need a java code to update the integer value if my input String matches with the string in file. please
uploading a text file into a database
uploading a text file into a database  how to upload a text file... { static File file; public static void main(String[] args) throws Exception { JLabel label=new JLabel("Choose File
problem of writing to a local file ( JApplet ) - Applet
problem of writing to a local file ( JApplet )  Dear All, I want to program a guestbook using java applets but now I have problem of writing... file into the applet code it is not working, means when i click the Submit button
how to update the text file?
how to update the text file?  my textfile with name list.txt: Rice... in my text file, if the item i entered matches with item in text file.how can i... 150 .... ....20 lines. java code: import java.io.*; import java.util.*; class
How to add download option for openwith and saveAs on exporting file to excel in servlet
How to add download option for openwith and saveAs on exporting file to excel... for generated .excel file to save at particular position on the system.Now as per...(); System.out.println("Your excel file has been generated!"); } catch
How to add download option for openwith and saveAs on exporting file to excel in servlet
How to add download option for openwith and saveAs on exporting file to excel... for generated .excel file to save at particular position on the system.Now as per...(); System.out.println("Your excel file has been generated!"); } catch
inserting text into text file using java application
inserting text into text file using java application  Hi, I want to insert a text or string into a text file using java application
Read Lines from text file
line based on a predefined size... Eg : If the 1st line of the text file... read from the text file and displays the output as desired. Unable to read the rest...Read Lines from text file  Here's a brief desc of what my Java code
Write Text into File
to write text into file. At last close output file using close() method... Write Text into File       In this example we are writing text into file.In
how to convert image file to text file?
how to convert image file to text file?  hi, can anybody tell how to convert image file to text file? plz help me
Read text File
Read text File  Hi,How can I get line and keep in a String in Java
how to display the output of the newly created excel file
how to display the output of the newly created excel file  the following program will create the test.xlsx file, how can i display the content of the test.xlsx file in the web browser? thanks, %@ page import
save text file - Java Beginners
save text file  hi i have just start programming in java.please guide me if i want to read a text file in java.then the text file is save in which directory
JavaScript write to text file
to write the text into the created file, we have used WriteLine() method. This code... JavaScript write to text file  ... are going to create a file and write text into it using JavaScript. In the given example
Converting Text Files into Bzip File
Converting Text Files into Bzip File  Hi, I am facing the problem during run the program, when converting text files into Bzip file. Please guide me how do i convert the text file into bzip file in PHP. I will welcome, if anyone
Creating a log in a text file - Applet
time it is run. I have figured of a way of writing the time to a text file using... as an application. Therefore i have added it onto a frame. I need to create a text file..."); Label label1 = new Label("Enter the file name:"); TextField text = new
Text field save as word file
Text field save as word file  Dear experts At run how to save set of text field contains text into single Word file. To save in our desktop computer. Solve my problem
Adding a text file - Java Beginners
Adding a text file  Hello, I need a program that will search a text file of strings representing numbers of type int and will write the largest and the smallest numbers to the screen. The file contains nothing but strings
Scanning a word in a TEXT document......
Scanning a word in a TEXT document......  Hi Genius persons... I'm having many resumes in my FOLDER called HARISH in D:(colon) i want to scan.....is it possible....??? S means give me the code
Scanning a word in a TEXT document......
Scanning a word in a TEXT document......  Hi Genius persons... I'm having many resumes in my FOLDER called HARISH in D:(colon) i want to scan.....is it possible....??? S means give me the code
Reading Text file and storing in map
Reading Text file and storing in map  Hi I have multiple text files. I want to read thoses files and store those records in map. Map will be of "LinkedHashMap<String, Map<String, String>>" type. Please let me know
Search and return lines of text file
Search and return lines of text file  I wrote the following code, that found lines of txt file with contains certain word, but it returns only the first or the last line! (However, the System.out.println show me all the lines
Write Text To File In New Line.
Write Text To File In New Line. In this tutorial you will learn how to write text into file in a new line. When you are writing in a file you may be required... WriteToFileNewLine Output : When you will execute this example a text file
Java search text file
Java search text file In this tutorial, you will learn how to search a text file in the current directory. For this, we have prompt the user to enter the name of a text file to search for. If the name does not have a .txt extension
Counting specific word occurences in a file
Counting specific word occurences in a file  Hello I have a log file from the proxy which consists all the browsing history with date,time,url,ip address etc as fields.Now i need to take only main part of the url like the domain
How to append text to an existing file in Java
How to append text to an existing file in Java  How to append text to an existing file in Java
Copy text file in a HTML form.
Copy Text File in a HTML form For copying a text file from one source to other... action into php code to copy the file. In PHP code, first begin the PHP tag, Define the source file and destination file variable. Copy file from source
Create text file at client's directory from server.
Create text file at client's directory from server.  Need java code to create text file at client's directory from server..... Please Help
take variables in text file and run in java
take variables in text file and run in java  I have a text file which have variables 17 10 23 39 13 33 How to take "17"in java code
Read Text file from Javascript - JSP-Servlet
Read Text file from Javascript  plz send the code How to Retrieve the data from .txt file thru Javascript? And how to find the perticular words in that file
stop word removal from text file
stop word removal from text file  i need java source code for stop word removal from a text file
How to write file text In New Line
How to write file text In New Line  Hi friends, How to write file... you went new text in new line. For this we created a new text file named... to write file text in New line in Java
Reading And Writing Excel File
to download the excel file and code first then make folder with the name of excel in C drive then copy the excel file and copy the code into webapps then follow... reading and writing excel file   
Advertisements
 

 

 

DMCA.com