【问题标题】:Java: replace only one line/string in the fileJava:仅替换文件中的一行/字符串
【发布时间】: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

这可能吗?

【问题讨论】:

标签: java string file file-io replace


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    您可以在首次更新时引入布尔变量并将其设置为 true。当您解析行时,在更新之前检查变量,只有在它为假时才更新。这样,您将使用包含目标字符串的第一行更新,无论是第二行还是其他行。

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

    【讨论】:

      猜你喜欢
      • 2021-05-01
      • 2014-03-21
      • 1970-01-01
      • 2011-06-30
      • 1970-01-01
      • 2018-10-29
      • 1970-01-01
      • 1970-01-01
      • 2022-06-16
      相关资源
      最近更新 更多