Katerina Tsellou
Katerina Tsellou

Reputation: 67

Make an array of words in alphabetical order in java, after reading them from a file

I've got the following code that opens and read a file and separates it to words. My problem is at making an array of these words in alphabetical order.

import java.io.*;

class MyMain {
    public static void main(String[] args) throws IOException {
        File file = new File("C:\\Kennedy.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
        String line = null;
        int line_count=0;
        int byte_count;
        int total_byte_count=0;
        int fromIndex;
        while( (line = br.readLine())!= null ){
            line_count++;
            fromIndex=0;
            String [] tokens = line.split(",\\s+|\\s*\\\"\\s*|\\s+|\\.\\s*|\\s*\\:\\s*");
            String line_rest=line;
            for (int i=1; i <= tokens.length; i++) {
                byte_count = line_rest.indexOf(tokens[i-1]);
                //if ( tokens[i-1].length() != 0)
                //System.out.println("\n(line:" + line_count + ", word:" + i + ", start_byte:" + (total_byte_count + fromIndex) + "' word_length:" + tokens[i-1].length() + ") = " + tokens[i-1]);
                fromIndex = fromIndex + byte_count + 1 + tokens[i-1].length();
                if (fromIndex < line.length())
                    line_rest = line.substring(fromIndex);
            }
            total_byte_count += fromIndex;
        }
    }
}

Upvotes: 1

Views: 282

Answers (2)

Elliott Frisch
Elliott Frisch

Reputation: 201497

I would read the File with a Scanner1 (and I would prefer the File(String,String) constructor to provide the parent folder). And, you should remember to close your resources explicitly in a finally block or you might use a try-with-resources statement. Finally, for sorting you can store your words in a TreeSet in which the elements are ordered using their natural ordering2. Something like,

File file = new File("C:/", "Kennedy.txt");
try (Scanner scanner = new Scanner(file)) {
    Set<String> words = new TreeSet<>();
    int line_count = 0;
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        line_count++;
        String[] tokens = line.split(",\\s+|\\s*\\\"\\s*|\\s+|\\.\\s*|\\s*\\:\\s*");
        Stream.of(tokens).forEach(word -> words.add(word));
    }
    System.out.printf("The file contains %d lines, and in alphabetical order [%s]%n",
            line_count, words);
} catch (Exception e) {
    e.printStackTrace();
}

1Mainly because it requires less code.
2or by a Comparator provided at set creation time

Upvotes: 1

Bot
Bot

Reputation: 11

If you are storing the tokens in a String Array, use Arrays.sort() and get a naturally sorted Array. In this case as its String, you will get a sorted array of tokens.

Upvotes: 0

Related Questions