Java.io.File.list() Method

Advertisements


Description

The java.io.File.list(FilenameFilter filter) returns the array of files and directories in the directory defined by this abstract path name that satisfy the given filter. All names are accepted if the given filter is null.

Declaration

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

public String[] list(FilenameFilter filter)

Parameters

  • NA

Return Value

The method returns the array of files and directories in the directory defined by this abstract path name that satisfy the given 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.list(FilenameFilter filter) method.

package com.tutorialspoint;

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

public class FileDemo implements FilenameFilter {
   
   String str;
   
   // constructor takes string argument
   public FileDemo(String ext)
   {
      str="."+ext;
   }
   // main method
   public static void main(String[] args) {
      
      File f = null;
      String[] paths;
      
      try{      
         // create new file
         f = new File("c:/test");
         
         // create new filter
         FilenameFilter filter = new FileDemo("txt");
         
         // array of files and directory
         paths = f.list(filter);
         
         // for each name in the path array
         for(String path:paths)
         {
            // prints filename and directory name
            System.out.println(path);
         }
      }catch(Exception e){
         // if any error occurs
         e.printStackTrace();
      }
   }

   @Override
   public boolean accept(File dir, String name) {
      return name.endsWith(str);
   }
}

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

child_test.txt



Advertisements
Advertisements