In: Computer Science
Write a Java program that reads words from a text file and displays all the non-duplicate words in ascending order. The text file is passed as a command-line argument.
Command line argument: test2001.txt
Correct output:
Words in ascending order...
1mango
Salami
apple
banana
boat
zebra
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;
public class NonDuplicateWords {
public static void main(String[] args) {
if(args.length > 0) {
File file = new File(args[0]);
try {
Scanner fin = new Scanner(file);
Set<String> words = new TreeSet<>();
while (fin.hasNext()) {
words.add(fin.next());
}
System.out.println("Words in ascending order...");
for(String word: words) {
System.out.println(word);
}
fin.close();
} catch (FileNotFoundException e) {
System.out.println(file.getAbsolutePath() + " does not exists");
}
} else {
System.out.println("Error. please provide file name in command line argument.");
}
}
}