DmitryB DmitryB - 1 year ago 104
Java Question

How to get all text files from one folder using Java?

I need to read all ".txt" files from folder (user needs to select this folder).

Please advise how to do it?

Answer Source

you can use filenamefilter class it is pretty simple usage public static void main(String[] args) throws IOException {

    File f = new File("c:\\mydirectory");

    FilenameFilter textFilter = new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.toLowerCase().endsWith(".txt");

    File[] files = f.listFiles(textFilter);
    for (File file : files) {
        if (file.isDirectory()) {
        } else {
            System.out.print("     file:");


just create an filenamefilter instance an override accept method how you want

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download