Jan 202017

ADM

How to display the content of a directory in Java

  • 20 January 2017
  • ADM

 

 

 

How to display the content of a directory in Java - images/logos/java.jpg

 

Here is a simple method how to list all files and sub-directories within a specific directory.

Example

The key element in the example is the recursive method listFiles which applies to the current folder and all sub-folders.

package com.admfactory.io;

import java.io.File;

public class DirectoryList {
    public static void main(String[] args) {
	System.out.println("Directory content list example");
	System.out.println();
	String folderPath = "d:\\admfactory.com";

	File dir = new File(folderPath);
	System.out.println("Folder: " + dir.getAbsolutePath());
	System.out.println();

	listFiles(dir);
    }

    public static void listFiles(File currentFile) {
	System.out.println(currentFile.getAbsolutePath());
	
	/** if is a folder take all files and sub-directories */
	if (currentFile.isDirectory()) {
	    File[] files = currentFile.listFiles();
	    for (File child : files) {
		listFiles(child);
	    }
	}

    }
}

Output

Directory content list example

Folder: d:\admfactory.com

d:\admfactory.com
d:\admfactory.com\dir1
d:\admfactory.com\dir1\f1.txt
d:\admfactory.com\dir1\f2.txt
d:\admfactory.com\dir1\f3.txt
d:\admfactory.com\dir1\f4.txt
d:\admfactory.com\dir1\f5.txt
d:\admfactory.com\dir1\f6.txt
d:\admfactory.com\dir1\f7.txt
d:\admfactory.com\dir2
d:\admfactory.com\dir2\f1.txt
d:\admfactory.com\dir2\f2.txt
d:\admfactory.com\dir2\f3.txt

 

 

 

References