【发布时间】:2012-11-04 13:05:04
【问题描述】:
我在 StringBuffer 中有一个文件的内容。该文件的内容包括多行(而不是单行)。我想编辑从索引 4(仅作为示例)到该行末尾的行的内容。我使用replace() 来编辑StringBuffer 的内容。
重点是replace方法有起始索引和结束索引等参数。但我不知道结束索引是什么,因为每一行的字符数不同
我想用str.indexOf("\n")找到行的结束索引,但是文件有很多行,所以会返回不正确的结果。
这是readFile(),如果您需要阅读代码
谢谢
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 的方法...
标签: java replace stringbuffer