我想重寫這本詞典:dictionary.txt按長度排序,而不是按字母順序排序。我有以下代碼(主要(字串[] args內)):BufferedWriter停止書寫
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();
MyComparator:
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嗎?如果是這樣,我怎樣才能使用它,而不會覆蓋已經寫好的內容?
沒有字符被消耗(a被轉換爲字符),但這可能是一個好主意。 – Justin
想知道爲什麼我沒有想到循環列表? – Justin
我同意這是一個不好的做法,但這是另一個問題。真正的「缺失8」問題是缺少新的線路。 –