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

วิธีลบสตริงเฉพาะในไฟล์ .txt ด้วย Java

เมธอด replaceAll(String regex, String replacement) แทนที่ substring ที่ match regex ด้วย replacement string เพื่อลบคำเฉพาะ ให้ replace ด้วย empty string ""

ขั้นตอน

  1. อ่านเนื้อหาไฟล์ทั้งหมดเป็น String
  2. ใช้ replaceAll() แทนที่คำที่ต้องการลบด้วย ""
  3. เขียนทับไฟล์เดิมด้วยผลลัพธ์

ตัวอย่างโค้ด


import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;

public class DeleteStringInFile {
    public static String fileToString(String filePath) throws Exception {
        Scanner sc = new Scanner(new File(filePath));
        StringBuffer sb = new StringBuffer();
        while (sc.hasNextLine()) {
            sb.append(sc.nextLine());
        }
        return sb.toString();
    }
    
    public static void main(String[] args) throws FileNotFoundException {
        String filePath = "D:\\sample.txt";
        String content = fileToString(filePath);
        System.out.println("Original: " + content);
        
        // ลบคำ "Tutorialspoint" (word boundary \b ป้องกันลบบางส่วนของคำอื่น)
        content = content.replaceAll("\\bTutorialspoint\\b", "");
        
        // เขียนทับไฟล์
        PrintWriter writer = new PrintWriter(new File(filePath));
        writer.append(content);
        writer.flush();
        
        System.out.println("After delete: " + fileToString(filePath));
    }
}

ผลลัพธ์


Original: Hello how are you welcome to Tutorialspoint
After delete: Hello how are you welcome to

Regex Pattern สำคัญ

เวอร์ชันปรับปรุง: จัดการ Newline และ Encoding


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

public class DeleteStringInFileBetter {
    public static void main(String[] args) throws IOException {
        Path path = Paths.get("D:\\sample.txt");
        
        // อ่านไฟล์ทั้งหมด (รองรับ UTF-8)
        String content = Files.readString(path, StandardCharsets.UTF_8);
        System.out.println("Original:\n" + content);
        
        // ลบคำ (case-insensitive, whole word)
        content = content.replaceAll("(?i)\\bTutorialspoint\\b", "");
        
        // เขียนทับ (เก็บ newline เดิมไว้)
        Files.writeString(path, content, StandardCharsets.UTF_8);
        
        System.out.println("After:\n" + Files.readString(path));
    }
}

ข้อควรระวัง

  • Backup ไฟล์ก่อน - การเขียนทับอาจสูญเสียข้อมูลหาก error ระหว่างทาง
  • ไฟล์ขนาดใหญ่ (>100MB) ควรอ่าน/เขียนทีละบรรทัด (streaming) แทนการโหลดทั้งไฟล์
  • Regex special characters ในคำที่จะลบ ต้อง escape: Pattern.quote(word)
  • Windows line ending (\r\n) vs Unix (\n) - ใช้ Files.readString จัดการอัตโนมัติ
Patternความหมายตัวอย่าง match
Tutorialspointลบทุกที่เจอ (รวมในคำอื่น)Tutorialspoint, MyTutorialspointX
\\bTutorialspoint\\bลบเฉพาะคำเต็ม (word boundary)Tutorialspoint ✓, MyTutorialspoint ✗
(?i)\\bTutorialspoint\\bไม่สนใจ case + word boundarytutorialspoint, TUTORIALSPOINT
\\s*Tutorialspoint\\s*ลบคำพร้อม whitespace รอบๆ" to Tutorialspoint " → " to "