Home > File > Tìm kiếm các file theo phần mở rộng trong Java

Tìm kiếm các file theo phần mở rộng trong Java

Sử dụng lớp FilenameFilter sẽ giúp bạn lọc ra các file thỏa mãn tiêu chí do bạn quy định ( chẳng hạn chỉ lấy các file có phần mở rộng “.txt” ).

Ví dụ :

package quyetdv.java.javaio.file;
import java.io.File;
import java.io.FilenameFilter;
public class FindFileExtensionExample {
    private static final String FILE_DIR = "C:\\test";
    private static final String FILE_TEXT_EXT = ".txt";
    public static void main(String[] args) {
        new FindFileExtensionExample().listFile(FILE_DIR, FILE_TEXT_EXT);
    public void listFile(String folder, String ext) {
        GenericExtFilter filter = new GenericExtFilter(ext);
        File dir = new File(folder);
        if (dir.isDirectory() == false) {
            System.out.println("Directory does not exists: " + FILE_DIR);
        // list out all the file name and filter by the extension
        String[] list = dir.list(filter);
        if (list.length == 0) {
            System.out.println("No files end with : " + FILE_TEXT_EXT);
        for (String file : list) {
            String temp = new StringBuffer(FILE_DIR).append(File.separator)
            System.out.println("file : " + temp);
    // 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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: