FileListFilter.java Source code

Java tutorial

Introduction

Here is the source code for FileListFilter.java

Source

import java.io.File;
import java.io.FilenameFilter;
import java.util.Date;

class FileListFilter implements FilenameFilter {
    private String name;
    private String extension;

    public FileListFilter(String name, String extension) {
        this.name = name;
        this.extension = extension;
    }

    public boolean accept(File directory, String filename) {
        boolean fileOK = true;
        if (name != null) {
            fileOK = filename.startsWith(name);
        }
        if (extension != null) {
            fileOK = filename.endsWith('.' + extension);
        }
        return fileOK;
    }
}

public class MainClass {
    public static void main(String[] args) {
        File myDir = new File("C:/");
        FilenameFilter select = new FileListFilter("F", "txt");
        File[] contents = myDir.listFiles(select);
        for (File file : contents) {
            System.out.println(file + " is a " + (file.isDirectory() ? "directory" : "file") + " last modified on\n"
                    + new Date(file.lastModified()));
        }
    }
}