【发布时间】:2015-09-04 17:52:35
【问题描述】:
我已使用以下代码将text 替换为word(取自here):
String targetFile = "filename";
String toUpdate = "text";
String updated = "word";
public static void updateLine() {
BufferedReader file = new BufferedReader(new FileReader(targetFile));
String line;
String input = "";
while ((line = file.readLine()) != null)
input += line + "\n";
input = input.replace(toUpdate, updated);
FileOutputStream os = new FileOutputStream(targetFile);
os.write(input.getBytes());
file.close();
os.close();
}
我有一个文件,我只想替换第二行 (text):
My text
text
text from the book
The best text
它工作正常,但它替换了文件中的所有toUpdate 字符串。如何编辑代码以仅替换文件中的一行/字符串(完全类似于 toUpdate 字符串)?
预期的文件应如下所示:
My text
word
text from the book
The best text
这可能吗?
【问题讨论】:
-
你需要真正理解代码,而不仅仅是复制粘贴。如果您了解它的作用,那么适应它就变得容易了。请注意,您发布的代码效率极低,并且有几个错误。阅读docs.oracle.com/javase/tutorial/essential/io/charstreams.html
标签: java string file file-io replace