Get all Files Present in a Directory in Java

Exercise:

Write a Java Program to get all files present in a directory.

1.List all files

Click Here to View the Solution!
 import java.io.File;
 public class Main {
   public static void main(String[] args) {
  
     // creates a file object
     File file = new File("C:\\Users\\Guest User\\Desktop\\Java File\\List Method");
  
     // returns an array of all files
     String[] fileList = file.list();
  
     for(String str : fileList) {
       System.out.println(str);
     }
   }
 } 
Click Here to View the Output!
.vscode 
file.txt
directory 
newFile.txt
Click Here to View the Explanation!
  • This program helps in fetching all the files existing in a directory.
  • In the first statement of main method, an object file has been instantiated specifying the path where the directories are stored.
  • In the next step method list is called by file instance.
  • All the files will be stored in a String type array fileList.
  • Then fileList array is iterated over by for-loop, that’ll print out all the files including sub-directories too, specified in the argument.

2.List files excluding Subdirectories

Click Here to View the Solution!
import java.io.File;
   public class Main {
   public static void main(String[] args) {
  
     try {
  
       File folder = new File("C:\\Users\\john Wales\\Desktop\\Java Article");
  
       // list all the files
       File[] files = folder.listFiles();
       for(File file : files) {
         if(file.isFile()) {
           System.out.println(file);
         }
       }
     } catch (Exception e) {
       e.getStackTrace();
     }
   }
 } 
Click Here to View the Output!
 C:\Users\Unknown\Desktop\Java Article\Language.class 
 C:\Users\Unknown\Desktop\Java Article\Languages.class 
 C:\Users\Unknown\Desktop\Java Article\Main.class
 C:\Users\Unknown\Desktop\Java Article\Main.java
 C:\Users\Unknown\Desktop\Java Article\sidebar.html
 C:\Users\Unknown\Desktop\Java Article\Test.class
 C:\Users\Unknown\Desktop\Java Article\Time.class
 C:\Users\Unknown\Desktop\Java Article\Time.java
Click Here to View the Explanation!
  • This program deals with listing out all the files, except sub-directories.
  • Just like in the previous example, in the first statement of main method, an object ‘folder’ is created.
  • Then ListFiles() method is called upon ‘folder’ object.
  • The resultant values are assigned to ‘File’ type array named ‘files’.
  • Then for-loop iterates over ‘files’, checking whether the value is a file or not using isFile() method in each iteration, and the results are displayed one by one.