Trong java, bạn có thể implements giao tiếp FilenameFilter và override phương thức accept(File dir, String name) để filter file theo phần mở rộng.
Ví dụ 1: implement giao tiếp FilenameFilter để liệt kê ra các file có phần mở rộng là ".txt", sau đó thực hiện xóa từng file.
import java.io.File; import java.io.FilenameFilter; public class DeleteFilesExample { private static final String FILE_DIR = "D:\\log"; private static final String FILE_TEXT_EXT = ".txt"; public static void main(String args[]) { new DeleteFilesExample().deleteFile(FILE_DIR, FILE_TEXT_EXT); } public void deleteFile(String folder, String ext) { GenericExtFilter filter = new GenericExtFilter(ext); File dir = new File(folder); // list out all the file name with .txt extension String[] list = dir.list(filter); // delete files if (list.length == 0) { File fileDelete; for (String file : list) { String temp = new StringBuffer(FILE_DIR).append(File.separator) .append(file).toString(); fileDelete = new File(temp); boolean isdeleted = fileDelete.delete(); System.out.println("file : " + temp + " is deleted : " + isdeleted); } } } // inner class, generic extension filter public class GenericExtFilter implements FilenameFilter { private String ext; public GenericExtFilter(String ext) { this.ext = ext; } public boolean accept(File dir, String name) { return (name.endsWith(ext)); } } }
Giả sử trong folder log có chứa các file: a.txt, b,txt, c.txt, d.txt:
Output:
file : D:\log\a.txt is deleted : true file : D:\log\b.txt is deleted : true file : D:\log\c.txt is deleted : true file : D:\log\d.txt is deleted : true
Ví dụ 2, Delete nhiều file trong java sử dụng lớp nặc danh
import java.io.File; import java.io.FilenameFilter; public class DeleteFilesExample2 { private static final String FILE_DIR = "D:\\log"; private static final String FILE_TEXT_EXT = ".txt"; public static void deleteFiles(String folder, String ext) { File dir = new File(folder); // list out all the file name with .txt extension String[] list = dir.list(new FilenameFilter() { @Override public boolean accept(File file, String name) { return name.endsWith(FILE_TEXT_EXT); } }); // delete files if (list.length == 0) { File fileDelete; for (String file : list) { String temp = new StringBuffer(FILE_DIR).append(File.separator) .append(file).toString(); fileDelete = new File(temp); boolean isdeleted = fileDelete.delete(); System.out.println("file : " + temp + " is deleted : " + isdeleted); } } } }
Giả sử trong folder log có chứa các file: a.txt, b,txt, c.txt, d.txt:
Output:
file : D:\log\a.txt is deleted : true file : D:\log\b.txt is deleted : true file : D:\log\c.txt is deleted : true file : D:\log\d.txt is deleted : true