Create a text file called random Words.text and a Java file called alphabeticalWords.java code example

Example: a program that reads words from a text file and displays all words in ascending alphabetical order

import java.util.*;
import java.io.*;


public class Task1 {
    public static void main(String[] args) throws Exception {
        // Check number of arguments passed

        if (args.length != 1) {
            System.out.println("Usage: TextFile");
            System.exit(0);

        }
String filename = args[0];

TreeSet<String>treeSet = new TreeSet<String>();
try
{
    Scanner in = new Scanner(new File(filename));
    String line;
    while ((line = in.nextLine())!=null)
    {
        String[] tokens = line.split("[||n|\t|\r|.|,|)|(|-|\"]");



        for (int i = 0; i  < tokens.length; i++)
        //for (int i = tokens.length -1; i >= 0; i--)
            treeSet.add(tokens[i]);

    }
}
catch (Exception ex)
{

}

Iterator iterator = treeSet.iterator();

System.out.println("\nDisplay words in ascending order");

while (iterator.hasNext()) {
System.out.println(iterator.next());

}
}
}

Tags:

Misc Example