繁体   English   中英

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

[英]Java: replace only one line/string in the file

我已经使用以下代码将text替换为word (从此处获取 ):

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

这可能吗?

而不是对整个字符串执行替换,而是在读取时进行。 这样,您可以计算行数并将其仅应用于第二行:

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;
}

您可以引入布尔变量,并在首次更新时将其设置为true。 解析行时,在执行更新之前检查变量,并且仅在变量为false时才进行更新。 这样,您将用包含目标String的第一行进行更新,无论是第二行还是其他。

您应该从文件读取时进行更新,以使其正常工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM