Đọ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
| Vấn đề | Giải pháp |
|---|---|
| File lớn → OOM | Dùng line-by-line processing (Scanner + PrintWriter streaming) |
| Regex special chars | Dùng Pattern.quote(str) nếu xóa chuỗi cố định |
| Word boundary | Dùng \\bword\\b để không xóa một phần từ |
| Encoding | Chỉ định UTF-8: new Scanner(file, "UTF-8"), new FileWriter(file, StandardCharsets.UTF_8) |