• Create a console application that reads text from a text file taken as a command line parameter and outputs the frequency (count) of the words that occur in the text file
o For example, the command will be run as “java FreqCounter input.txt”, and the output should be of the form: <word>,count
I tried it with the following code but the output comes as the first word of the text file and the count as 0. It repeats the same output for the complete file.
The code is as follows:
import java.io.*; class FreqCounter { //Code only reads a file public static void main(String args[]) { try{ // Open the file that is the first // command line parameter String nameOfFile = args[0]; String sample=""; String tokens[] = new String[1000]; int count; FileInputStream fstream = new FileInputStream(nameOfFile); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; //Read File Line By Line while ((strLine = br.readLine()) != null) { sample=""+strLine; } tokens = sample.split(" "); for (int i=0;i<=tokens.length;i++) { count=0; for(int j=i+1;j<=tokens.length;j++) { if (tokens[i]==tokens[j]) { count++; } System.out.println("Word: "+tokens[i]+","+count); } //Close the input stream in.close(); } } catch (Exception e){//Catch exception if any System.err.println("Error: " + e.getMessage()); } } }