我正在尝试重写这本字典:dictionary.txt按长度而不是按字母顺序排序。我有以下代码(在 main(String[] args) 内):
BufferedReader read = new BufferedReader(new FileReader(new File(DIC_READ_PATH)));
BufferedWriter write= new BufferedWriter(new FileWriter(DIC_WRITE_PATH),1);
ArrayList<String> toWrite = new ArrayList<String>();
for (int a = read.read(); a != -1; a = read.read()){
char c = (char) a;
toWrite.add("" + c + read.readLine());
}
read.close();
Collections.sort(toWrite, new MyComparator());
for (int a = 0; a <= 70000; a += 10000){
write.write(toWrite.subList(a, a + 10000).toString().replaceAll("[\\[,\\]]", "").replaceAll(" ", "\n"));
write.flush();
}
write.write(toWrite.subList(80000, toWrite.size()).toString().replaceAll("[\\[,\\]]", "").replaceAll(" ", "\n"));
write.close();
我的比较器:
public class MyComparator implements Comparator<String> {
@Override
public int compare(String arg0, String arg1) {
// TODO Auto-generated method stub
if (arg0.length() == arg1.length()){
return arg0.compareTo(arg1);
}
return arg0.length() < arg1.length() ? -1 : +1;
}
}
它对 Arraylist 进行了很好的排序,但是当我编写字符串时,它不会写 8 个单词。我尝试改变 BufferedWriter 上的缓冲区,发现较小的缓冲区有帮助,所以我将缓冲区设置为 1。我发现了这个:Buffered Writer Java Limit / Issues并尝试在每次写入和最后关闭时刷新(之后甚至改变缓冲区)。我仍然得到 80360 字而不是 80368。为什么它不写完整的单词列表?我必须使用另一个 BufferedWriter 吗?如果是这样,我如何使用它而不覆盖已经写入的内容?