在从文件中读取之后,在java中按字母顺序创建一个单词数组

时间:2016-03-13 17:11:54

标签: java arrays file

我有以下代码打开并读取文件并将其分隔为单词。 我的问题是按字母顺序排列这些单词的数组。

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;
        }
    }
}

2 个答案:

答案 0 :(得分:1)

我会使用Scanner 1 阅读File(我希望File(String,String)构造函数提供父文件夹)。而且,您应该记住在close中明确finally您的资源,您可以使用try-with-resources statement。最后,对于排序,您可以将字词存储在TreeSet中,其中使用natural ordering 对元素进行排序 2 。像,

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();
}

1 主要是因为它需要更少的代码。
2 或由设置创建时提供的Comparator

答案 1 :(得分:0)

如果要将标记存储在字符串数组中,请使用Arrays.sort()并获取自然排序的数组。在这种情况下,作为其String,您将获得一个已排序的标记数组。