2012-11-15 77 views
0

我擁有StringBuffer中的文件內容。該文件的內容包含很多行(不在一行中)。我想編輯從索引4(例如)到該行結尾的一行內容。我使用replace()來編輯StringBuffer的內容。Java StringBuffer:將起始索引中的內容替換爲行尾

重點在於替換方法有參數,如起始索引和結束索引。但我不知道什麼是結束指數,因爲每行有不同的字符數

我想用str.indexOf("\n")找到行的結尾索引,但是文件有很多行,所以它會返回不正確的結果。

這是readFile()如果u需要讀取的代碼

謝謝

public StringBuffer readFile(){ //read file line by line 
    File f = getFilePath(fileName); 
    StringBuffer sb = new StringBuffer(); 
    String textinLine; 

    try { 
     FileInputStream fs = new FileInputStream(f); 
     InputStreamReader in = new InputStreamReader(fs); 
     BufferedReader br = new BufferedReader(in); 

    while (true){ 
      textinLine = br.readLine(); 
      if (textinLine == null) break; 
      sb.append(textinLine+ "\n"); 
     } 
     fs.close(); 
     in.close(); 
     br.close(); 
    } ... // just some catch statements heres 
} 
+0

在追加到StringBuffer之前,爲什麼不在讀入時分別將每條線的變化應用到每行中? (順便說一下,使用StringBuilder來代替,它的速度更快) –

+0

b/c我需要再次讀取文件,以便我編寫一個讀取文件並返回StringBuffer的方法。 – kaboom

回答

0

使用String.indexOf()爲你指出的,但是傳遞的起始位置,例如indexOf('\n', 4);

0

我同意Jim的想法,爲什麼不在將字符串附加到StringBuffer之前處理字符串。

順便說一句,我認爲你可以使用indexOf(String str, int fromIndex)函數來分析的StringBuffer,每一次當你'\n',你可以設置一個偏移值,那麼下一次,當你下一次\n,你可以讓指數值加上偏移量。