我是Java新手。我试图从文本文件中添加几个单词到我现有的基于文本的单词列表。我有以下代码在做
“wordList”是一个包含现有单词的arraylist。
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
答案 0 :(得分:5)
Collections.sort(wordList);
将完美运作。如果需要忽略这个案例,那么请使用下面的代码。
Collections.sort(wordList,String.CASE_INSENSITIVE_ORDER);