Loiane Groner, Brazilian, works as a Java/ Sencha evangelist. She has 7+ years of experience in web development. She is the ESJUG (Espirito Santo Java Users Group) and CampinasJUG (Campinas Java Users Group) leader and coordinator. Loiane is passionate about technology and programming. Also author of ExtJS 4 First Look book. Loiane is a DZone MVB and is not an employee of DZone and has posted 42 posts at DZone. You can read more from them at their website. View Full User Profile

Java Example: List all Files from a Directory (or Subdirectory)

06.25.2012
| 42788 views |
  • submit to reddit

This is a basic algorithm, but it can be very useful in some situations and very handy for those that are learning Java.

The class bellow contains 4 methods:

  1. the first one will list all the files and folder names under a directory
  2. the second one will list all the file names under a directory
  3. the third one will list all the folder names under a directory
  4. the fourth one will list all the files from the directory and its sub-directories (be carefull with this one!)

Following is the code:

package com.loiane.util;
 
import java.io.File;
 
/**
 * Contains some methods to list files and folders from a directory
 *
 * @author Loiane Groner
 * http://loiane.com (Portuguese)
 * http://loianegroner.com (English)
 */
public class ListFilesUtil {
 
    /**
     * List all the files and folders from a directory
     * @param directoryName to be listed
     */
    public void listFilesAndFolders(String directoryName){
 
        File directory = new File(directoryName);
 
        //get all the files from a directory
        File[] fList = directory.listFiles();
 
        for (File file : fList){
            System.out.println(file.getName());
        }
    }
 
    /**
     * List all the files under a directory
     * @param directoryName to be listed
     */
    public void listFiles(String directoryName){
 
        File directory = new File(directoryName);
 
        //get all the files from a directory
        File[] fList = directory.listFiles();
 
        for (File file : fList){
            if (file.isFile()){
                System.out.println(file.getName());
            }
        }
    }
 
    /**
     * List all the folder under a directory
     * @param directoryName to be listed
     */
    public void listFolders(String directoryName){
 
        File directory = new File(directoryName);
 
        //get all the files from a directory
        File[] fList = directory.listFiles();
 
        for (File file : fList){
            if (file.isDirectory()){
                System.out.println(file.getName());
            }
        }
    }
 
    /**
     * List all files from a directory and its subdirectories
     * @param directoryName to be listed
     */
    public void listFilesAndFilesSubDirectories(String directoryName){
 
        File directory = new File(directoryName);
 
        //get all the files from a directory
        File[] fList = directory.listFiles();
 
        for (File file : fList){
            if (file.isFile()){
                System.out.println(file.getAbsolutePath());
            } else if (file.isDirectory()){
                listFilesAndFilesSubDirectories(file.getAbsolutePath());
            }
        }
    }
 
    public static void main (String[] args){
 
        ListFilesUtil listFilesUtil = new ListFilesUtil();
 
        final String directoryLinuxMac ="/Users/loiane/test";
 
        //Windows directory example
        final String directoryWindows ="C://test";
 
        listFilesUtil.listFiles(directoryLinuxMac);
    }
}
Published at DZone with permission of Loiane Groner, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Zheng Dan replied on Tue, 2012/06/26 - 9:40am

final String directoryWindows ="C:\\test";it must be two backslash during Windows directories,it's just a typo

Ralph Schaer replied on Wed, 2012/07/04 - 5:53am

It's worth mentioning that Java 7 introduced an enhanced IO Api. NIO.2. This api allows you to write directory walking code without recursion with the visitor pattern. More information in the Java Tutorial: 

http://docs.oracle.com/javase/tutorial/essential/io/walk.html

public class F {
public static class FileVisitor extends SimpleFileVisitor<Path> {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
System.out.println(file.toRealPath());
return FileVisitResult.CONTINUE;
}
}
	
public static void main(String[] args) throws IOException {
Path startingDir = Paths.get("e:\\temp");
FileVisitor visitor = new FileVisitor();

/* List all files from a directory and its subdirectories */
Files.walkFileTree(startingDir, visitor);

/* List all the files and directories under a directory */
Files.walkFileTree(startingDir, EnumSet.of(FileVisitOption.FOLLOW_LINKS), 1, visitor);

}
}

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.