Java:仅替换文件中的一行/字符串

标签 java string file file-io replace

我使用以下代码将 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/

相关文章:

php - 只有一个文件上传文件和内部服务器错误,其他都可以

java - java中的 super 接口(interface)

Java代码如何将颜色附加到列表一定次数

python - 将引号作为 python 列表中的字符

java - 将一个字符串分成两部分

c - 如何更改二叉树中字符串的值?

file - 从文件中读取 n 个字节的文本

java - 使用 BitmapFactory 加载多个图像 [OutOfMemoryException]

java - Java 中两个对象可以相互包含吗?

java - 在多维 ArrayList 中查找字符串