DmitryB DmitryB - 1 month ago 10x
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?


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