Java.io.File.listFiles() Method

Advertisements


Description

The java.io.File.listFiles() returns the array of abstract pathnames defining the files in the directory denoted by this abstract pathname.

Declaration

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

public File[] listFiles()

Parameters

  • NA

Return Value

The method returns an array of pathnames for files and directories in the directory denoted by this abstract pathname.

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() method.

package com.tutorialspoint;

import java.io.File;

public class FileDemo {
   public static void main(String[] args) {
      
      File f = null;
      File[] paths;
      
      try{      
         // create new file
         f = new File("c:/test");
         
         // returns pathnames for files and directory
         paths = f.listFiles();
         
         // 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
c:\test\child_test.txt
c:\test\child_test.xlsx




Advertisements
Advertisements