Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Cách ghi đè (overwrite) một dòng trong file .txt bằng Java

Java không hỗ trợ sửa file in-place (trực tiếp trên disk). Cách làm: Đọc toàn file → Sửa trong bộ nhớ → Ghi đè file.

Quy trình

  1. Đọc file vào String (dùng Scanner + StringBuilder).
  2. Dùng replaceAll(oldLine, newLine) thay thế dòng cần sửa.
  3. Ghi lại file bằng FileWriter.

Ví dụ hoàn chỉnh

import java.io.*;
import java.util.Scanner;

public class OverwriteLine {
    public static void main(String args[]) throws IOException {
        String filePath = "D://input.txt";
        
        // 1. Đọc file vào String
        Scanner sc = new Scanner(new File(filePath));
        StringBuilder buffer = new StringBuilder();
        while (sc.hasNextLine()) {
            buffer.append(sc.nextLine()).append(System.lineSeparator());
        }
        sc.close();
        String fileContents = buffer.toString();
        System.out.println("Nội dung gốc:\n" + fileContents);
        
        // 2. Thay thế dòng
        String oldLine = "No preconditions and no impediments. Simply Easy Learning!";
        String newLine = "Enjoy the free content";
        fileContents = fileContents.replaceAll(oldLine, newLine);
        
        // 3. Ghi đè file
        FileWriter writer = new FileWriter(filePath);
        writer.write(fileContents);
        writer.flush();
        writer.close();
        
        System.out.println("Đã ghi đè. Nội dung mới:\n" + fileContents);
    }
}

Kết quả

Nội dung gốc:
... No preconditions and no impediments. Simply Easy Learning!

Đã ghi đè. Nội dung mới:
... Enjoy the free content

Lưu ý quan trọng

  • replaceAll(regex, replacement): Tham số đầu là regex. Nếu dòng chứa ký tự đặc biệt regex (., *, (, )...), phải escape: Pattern.quote(oldLine).
  • File lớn: Không nên đọc hết vào RAM. Dùng file tạm: đọc dòng → ghi file tạm → rename.
  • Encoding: FileWriter dùng default charset. Khuyên dùng new FileWriter(file, StandardCharsets.UTF_8) (Java 11+) hoặc OutputStreamWriter.

Version an toàn cho file lớn (Java 7+)

Path path = Paths.get("D://input.txt");
Path temp = Files.createTempFile("temp", ".txt");

try (BufferedReader reader = Files.newBufferedReader(path);
     BufferedWriter writer = Files.newBufferedWriter(temp)) {
    String line;
    while ((line = reader.readLine()) != null) {
        if (line.equals(oldLine)) line = newLine;
        writer.write(line);
        writer.newLine();
    }
}
Files.move(temp, path, StandardCopyOption.REPLACE_EXISTING);