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

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()) {
                System.out.print("directory:");
            } else {
                System.out.print("     file:");
            }
            System.out.println(file.getCanonicalPath());
        }

    }

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


Assuming you already have the directory, you can do something like this:

File directory= new File("user submits directory");
for (File file : directory.listFiles())
{
   if (FileNameUtils.getExtension(file.getName()).equals("txt"))
   {
       //dom something here.
   }
}

The FileNameUtils.getExtension() can be found here.

Edit: What you seem to want to do is to access the file structure from the web browser. According to this previous SO post, what you want to do is not possible due to security reasons.

Tags:

Java

File