2013-04-01 27 views
-1

我想重寫這本詞典: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嗎?如果是這樣,我怎樣才能使用它,而不會覆蓋已經寫好的內容?

回答

2

你是消費輸入數據的隨機字符:

for (int a = read.read(); a != -1; a = read.read()){ 

不混合read()readLine()電話。只需使用readLine()並測試爲空。

此外,爲了編寫結果,請勿使用List.toString impl和討厭的正則表達式替換,只是在列表中循環並寫入一個單詞後跟一個換行符。

+0

沒有字符被消耗(a被轉換爲字符),但這可能是一個好主意。 – Justin

+0

想知道爲什麼我沒有想到循環列表? – Justin

+0

我同意這是一個不好的做法,但這是另一個問題。真正的「缺失8」問題是缺少新的線路。 –

1

我認爲這個問題是在這裏:

for (int a = 0; a <= 70000; a += 10000){ 
     write.write(toWrite.subList(a, a + 10000).toString().replaceAll("[\\[,\\]]", "").replaceAll(" ", "\n")); 
     write.flush(); 
    } 

你應該write.write( 「\ n」);在沖洗之前。

+0

如果你看看最後的結果,每個''用'\ n'代替,所以不需要write.write(「\ n」) – Justin

+0

但是最後將沒有空間。 ;)8次迭代是否有趣? –

+0

好點。這可能是問題所在。 – Justin