Home > File > Xóa các file theo phần mở rộng trong Java

Xóa các file theo phần mở rộng trong Java

Trong Java, bạn có thể implements lớp FilenameFilter, override phương thức accept(File dir, String name) để thực hiện chức năng lọc file.

Ví dụ sau minh họa cách sử dụng FilenameFilter để liệt kê tất cả các file có phần mở rộng “.txt” trong thư mục “C:\\test”, sau đó xóa nó.

package quyetdv.java.javaio.file;
import java.io.File;
import java.io.FilenameFilter;
public class DeleteFileExtensionExample {
    private static final String FILE_DIR = "C:\\test";
    private static final String FILE_TEXT_EXT = ".txt";
    public static void main(String[] args) {
        new DeleteFileExtensionExample().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);
       if (list.length == 0) {
       File fileDelete;
       for (String file : list) {
           String temp = new StringBuffer(FILE_DIR).append(File.separator)
           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);
Categories: File
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: