Java-根据文件后缀名删除文件

Java-根据文件后缀名删除文件

Tags: Java

摘要

Java-根据文件后缀名删除文件

FilenameFilter

可以实现接口FilenameFilter,覆盖accept(File dir, String name)方法,实现文件过滤功能。

删除指定后缀文件例子

这个例子是删除/home/zhu/folder文件夹下的.txt后缀的文件

package cn.javacore.io.file;

import java.io.File;
import java.io.FilenameFilter;

public class _10_FileChecker {


    private static final String FILE_DIR = "/home/zhu/folder";
    private static final String FILE_TEXT_EXT = ".txt";

    public static void main(String args[]) {
        new _10_FileChecker().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) return;

        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.toLowerCase().endsWith(ext.toLowerCase()));
        }
    }
}