Java.io.File.listFiles() Method

Advertisements


Description

The java.io.File.listFiles(FilenameFilter filter) returns an array of abstract pathnames indicating the files and directories in the directory indicated by this abstract pathname that satisfy the specified filter.

Declaration

Following is the declaration for java.io.File.listFiles(FilenameFilter filter) method:

public File[] listFiles(FilenameFilter filter)

Parameters

  • filter - Filename filter

Return Value

The method returns an array of abstract pathnames indicating the files and directories in the directory indicated by this abstract pathname that satisfy the specified filter.

Exception

  • SecurityException -- If a security manager exists and its SecurityManager.checkRead(java.lang.String) method denies read access to the file

Example

The following example shows the usage of java.io.File.listFiles(FilenameFilter filter) method.

package com.tutorialspoint;

import java.io.File;
import java.io.FilenameFilter;

public class FileDemo {
   public static void main(String[] args) {
      
      File f = null;
      File[] paths;
      
      try{      
         // create new file
         f = new File("c:/test");
         
         // create new filename filter
         FilenameFilter fileNameFilter = new FilenameFilter() {
   
            @Override
            public boolean accept(File dir, String name) {
               if(name.lastIndexOf('.')>0)
               {
                  // get last index for '.' char
                  int lastIndex = name.lastIndexOf('.');
                  
                  // get extension
                  String str = name.substring(lastIndex);
                  
                  // match path name extension
                  if(str.equals(".txt"))
                  {
                     return true;
                  }
               }
               return false;
            }
         };
         // returns pathnames for files and directory
         paths = f.listFiles(fileNameFilter);
         
         // for each pathname in pathname array
         for(File path:paths)
         {
            // prints file and directory paths
            System.out.println(path);
         }
      }catch(Exception e){
         // if any error occurs
         e.printStackTrace();
      }
   }
}

Let us compile and run the above program, this will produce the following result:

c:\test\child_test.txt




Advertisements
Advertisements