Write a program CountWords in Java that reads text from a fi
Write a program CountWords in Java that reads text from a file and breaks it up into individual words. Insert the words into a tree set. At the end of the input file, print all words, followed by the size of the resulting set. This program determines how many unique words a text file has. If the file is not found, give the user a chance to select another file.
Solution
Code:
package chegg;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;
import java.util.TreeSet;
import javax.swing.text.html.HTMLDocument.Iterator;
public class Test {
public static void main(String args[]) throws IOException
{
BufferedReader br = null;
String sCurrentLine;
TreeSet<String> ts = new TreeSet<String>();
br = new BufferedReader(new FileReader(\"C:/Users/ansharm5/Desktop/chegg\"));
while ((sCurrentLine = br.readLine()) != null) {
StringTokenizer st = new StringTokenizer(sCurrentLine);
while(st.hasMoreTokens())
{
ts.add(st.nextToken());
}
}
System.out.println(\"Total no. of words: \"+ ts.size());
java.util.Iterator<String> iterator = ts.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next() + \" \");
}
}
}
