Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

วิธี Overwrite บรรทัดในไฟล์ .txt ด้วย Java

Java ไม่มีเมธอด Overwrite บรรทัดโดยตรง ต้อง: อ่านทั้งไฟล์ -> แทนที่ข้อความใน Memory -> เขียนทับไฟล์เดิม

ขั้นตอน

  1. อ่านไฟล์ทั้งหมดเข้า String (Scanner + StringBuilder)
  2. ใช้ replaceAll(oldLine, newLine) แทนที่บรรทัดเป้าหมาย
  3. เขียน String ใหม่ทับไฟล์เดิม (FileWriter)

ตัวอย่างโค้ดครบถ้วน

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class OverwriteLineInFile {
    public static void main(String[] args) throws IOException {
        String filePath = "D:/input.txt";
        
        // 1. อ่านไฟล์ทั้งหมด
        StringBuilder buffer = new StringBuilder();
        try (Scanner sc = new Scanner(new File(filePath))) {
            while (sc.hasNextLine()) {
                buffer.append(sc.nextLine()).append(System.lineSeparator());
            }
        }
        String fileContents = buffer.toString();
        System.out.println("Original:\n" + fileContents);
        
        // 2. แทนที่บรรทัดที่ต้องการ
        String oldLine = "No preconditions and no impediments. Simply Easy Learning!";
        String newLine = "Enjoy the free content";
        fileContents = fileContents.replaceAll(oldLine, newLine);
        
        // 3. เขียนทับไฟล์เดิม
        try (FileWriter writer = new FileWriter(filePath)) {
            writer.write(fileContents);
        }
        
        System.out.println("Updated:\n" + fileContents);
    }
}

ผลลัพธ์

Original:
Tutorials Point originated from the idea... Simply Easy Learning!

Updated:
Tutorials Point originated from the idea... Enjoy the free content

ข้อควรระวัง

  • replaceAll(regex, replacement) ใช้ Regex -> ตัวอักษรพิเศษต้อง Escape (., *, ?, +, [, ], (, ), {, }, |, ^, $, \\)
  • ใช้ Pattern.quote(oldLine) หาก Old Line มี Special Characters
  • FileWriter เขียนทับไฟล์เดิม (Truncate) โดย Default
  • ไฟล์ใหญ่: ควรอ่าน/เขียนแบบ Streaming (Line by Line) ไม่โหลดทั้งไฟล์เข้ Memory

เวอร์ชัน Streaming (สำหรับไฟล์ใหญ่)

import java.io.*;
import java.nio.file.*;

public class OverwriteLineStreaming {
    public static void main(String[] args) throws IOException {
        Path source = Paths.get("D:/input.txt");
        Path temp = Files.createTempFile("temp", ".txt");
        
        String oldLine = "Old Line";
        String newLine = "New Line";
        
        try (BufferedReader reader = Files.newBufferedReader(source);
             BufferedWriter writer = Files.newBufferedWriter(temp)) {
            
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.equals(oldLine)) {
                    writer.write(newLine);
                } else {
                    writer.write(line);
                }
                writer.newLine();
            }
        }
        
        // แทนที่ไฟล์เดิมด้วยไฟล์ Temp (Atomic)
        Files.move(temp, source, StandardCopyOption.REPLACE_EXISTING);
    }
}

สรุป

  • ไฟล์เล็ก: อ่านทั้งหมด -> replaceAll() -> เขียนทับ (Simple)
  • ไฟล์ใหญ่: Streaming Line-by-Line เขียน Temp File -> Move แทนที่ (Memory Efficient)
  • ใช้ Files.move(..., REPLACE_EXISTING) สำหรับ Atomic Replace