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

Xóa chuỗi con khỏi file text trong Java (replaceAll)

Đọc toàn file vào chuỗi, dùng replaceAll(regex, replacement) để xóa (thay bằng chuỗi rỗng), ghi đè file.

Ví dụ: Xóa từ "Tutorialspoint"


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

public class DeleteStringFromFile {
    public static String readFile(String path) throws IOException {
        StringBuilder sb = new StringBuilder();
        try (Scanner sc = new Scanner(new File(path))) {
            while (sc.hasNextLine()) {
                sb.append(sc.nextLine()).append("\n");
            }
        }
        return sb.toString();
    }
    
    public static void main(String[] args) throws IOException {
        String path = "D:/sample.txt";
        
        String content = readFile(path);
        System.out.println("Trước: " + content);
        
        // Xóa từ "Tutorialspoint" (word boundary \b tránh xóa một phần từ)
        String updated = content.replaceAll("\\bTutorialspoint\\b", "");
        
        // Ghi đè file
        try (PrintWriter pw = new PrintWriter(new FileWriter(path))) {
            pw.print(updated);
        }
        
        System.out.println("Sau: " + readFile(path));
    }
}

Kết quả


Trước: Hello how are you welcome to Tutorialspoint
Sau: Hello how are you welcome to

⚠️ Các lưu ý quan trọng

Phiên bản streaming (file lớn)


try (Scanner sc = new Scanner(new File(in), "UTF-8");
     PrintWriter pw = new PrintWriter(new FileWriter(out, StandardCharsets.UTF_8))) {
    while (sc.hasNextLine()) {
        String line = sc.nextLine();
        pw.println(line.replaceAll("\\bTutorialspoint\\b", ""));
    }
}
Vấn đềGiải pháp
File lớn → OOMDùng line-by-line processing (Scanner + PrintWriter streaming)
Regex special charsDùng Pattern.quote(str) nếu xóa chuỗi cố định
Word boundaryDùng \\bword\\b để không xóa một phần từ
EncodingChỉ định UTF-8: new Scanner(file, "UTF-8"), new FileWriter(file, StandardCharsets.UTF_8)