java – Create a Dictionary from a text file.
It takes a text file as input and outputs all the words in that file in alphabetical order, one word per line, ignoring duplicates.
[cc lang=”java” tab_size=”2″ lines=”105″]
import java.io.*;
import java.util.*;
public class Dictionary {
public static void main(String[] args) {
try{
FileReader fr = new FileReader(“words.txt”);
BufferedReader br = new BufferedReader(fr);
String s;
String word = null;
String[] arrayWords;
ArrayList aListWords = new ArrayList();
int j = 0;while((s = br.readLine()) != null) {
Scanner scan = new Scanner(s);
while (scan.hasNext()) {
word = scan.next().toLowerCase();
aListWords.add(word);
j++;
}
}
br.close();
fr.close();
removeDuplicates(aListWords);
Collections.sort(aListWords);
int size = aListWords.size();
for(int i = 0; i < size ; i++){
System.out.println( aListWords.get( i ) );
}
System.out.println(j);
} catch (Exception e){//Catch exception if any
System.err.println(“Error: ” + e.getMessage());
}
}
public static void removeDuplicates(ArrayList aList) {
HashSet h = new HashSet(aList);
aList.clear();
aList.addAll(h);
}
}
[/cc]
Leave a Reply