我擁有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
}
在追加到StringBuffer之前,爲什麼不在讀入時分別將每條線的變化應用到每行中? (順便說一下,使用StringBuilder來代替,它的速度更快) –
b/c我需要再次讀取文件,以便我編寫一個讀取文件並返回StringBuffer的方法。 – kaboom