Read File And Count Occurrence Of Word In Java

Read a file and count the occurrence of word in java

import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.TreeMap;
import java.util.StringTokenizer;

public class fileRead {

public static void main(String [] args){

try{

String textFile =”D:\workspace\datastructure\src\javaprogram\test.txt”;
BufferedReader input = new BufferedReader(new FileReader(textFile));

//Creating the Map to store the words and their occurrences
TreeMap<String, Integer> frequencyMap = new TreeMap<String, Integer>();
String currentLine = null;

//Reading line by line from the text file
while((currentLine = input.readLine()) != null){

//Parsing the words from each line
StringTokenizer parser = new StringTokenizer(currentLine, ” tnrf.,;:!?'””);
while(parser.hasMoreTokens()){
String currentWord = parser.nextToken();

Integer frequency = frequencyMap.get(currentWord);
if(frequency == null){
frequency = 0;
}
//Putting each word and its occurrence into Map
frequencyMap.put(currentWord, frequency + 1);
}

}

//Displaying the Result
System.out.println(frequencyMap);

}catch(IOException ie){
ie.printStackTrace();
System.err.println(“Your entered path is wrong”);
}

}

}

Leave a Reply

Your email address will not be published. Required fields are marked *

85 + = 95