簡體   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