我使用以下代码将 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();
}
我有一个文件,我只想替换第二行(文本
):
My text
text
text from the book
The best text
它工作正常,但它替换了文件中的所有 toUpdate
字符串。如何编辑代码以仅替换文件中的一行/字符串(完全类似于 toUpdate
字符串)?
预期的文件应如下所示:
My text
word
text from the book
The best text
这可能吗?
最佳答案
不要对整个字符串执行替换,而是在读取时执行替换。这样您就可以计算行数并仅将其应用于第二行:
BufferedReader file = new BufferedReader(new FileReader(targetFile));
String line;
String input = "";
int count = 0;
while ((line = file.readLine()) != null) {
if (count == 1) {
line = line.replace(toUpdate, updated);
}
input += line + "\n";
++count;
}
但请注意,在字符串上使用 +
运算符(尤其是在循环中)通常是一个坏主意,您可能应该使用 StringBuilder
来代替:
BufferedReader file = new BufferedReader(new FileReader(targetFile));
String line;
StringBuilder input = new StringBuilder();
int count = 0;
while ((line = file.readLine()) != null) {
if (count == 1) {
line = line.replace(toUpdate, updated);
}
input.append(line).append('\n');
++count;
}
关于Java:仅替换文件中的一行/字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30926421/