0

我是 Java 新手。我正在尝试将文本文件中的几个单词添加到我现有的基于文本的单词列表中。我有下面的代码

  1. 将文件中的单词添加到现有列表
  2. 对单词列表进行排序
  3. 将单词保存到文本文件

“wordList”是一个包含现有单词的数组列表。

    private void updateDictionaryFile(String filepath) {
    String textCurrentLine = "";

    BufferedReader dictionaryFile = null;
    try {

        Scanner fileScanner = new Scanner(new File(filepath));
        while(fileScanner.hasNextLine()){
            System.out.println("fileScanner.hasNextLine()  "+  fileScanner.hasNextLine());
            textCurrentLine = fileScanner.nextLine();
            if(textCurrentLine.length() > 0)
            if (!wordList.contains(textCurrentLine)) {
                wordList.add(textCurrentLine);
            }
        }

        Collections.sort(wordList);

        String newFile = filepath.replace(".txt", "_new.txt");
        PrintWriter pw = new PrintWriter(new FileOutputStream(newFile));
        for (int i = 0; i < wordList.size(); i++) {
            pw.println(wordList.get(i).toString());
        }
        pw.close();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (dictionaryFile != null) {
                dictionaryFile.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

新文件中列出的单词未排序。我在两者之间错过了什么吗?

下面是输出

A
Achieve
Although
Anything
Ask
Avoid
Badly
Bluma
But
Find
Forget
Goal
Goals
How
In
It
Just
Keep
Know
NOT
Often
Once
One
Psychologists
Reasoning
Reject
Remember
Research
Russian
Shifting
Sidestep
So
Sometimes
Start
Stop
The
This
Those
Under
Visualise
Visualising
We
What
When
With
You
Zeigarnik
a
aa
aah
aahed
aahing
aahs
aal
aalii
aaliis
aals
aardvark
aardwolf
aargh
aarrgh
aarrghh
aas
4

1 回答 1

5

Collections.sort(wordList);将完美地工作。如果需要忽略这种情况,请使用下面的代码。

Collections.sort(wordList,String.CASE_INSENSITIVE_ORDER);
于 2013-11-05T11:55:16.413 回答