Recent Tutorials and Articles
    Printing File Names Recursively in a Directory
    Published on: 19th January 2019

    This tutorial describes how to print names of the files in a directory and all of its subdirectories.

    Problem Statement

    Print all the file names recrusively in a given directory.


    1. Files can be printed in any order.
    2. Multi-threading needs to be utilized to make program faster on multi-core machines.



    This problem can be easily solved using recursion as we can simply create a method to print file names in a directory and then call itself for every sibdirectory.

    However since we need to use multi-threading, we will use ForkJoinPool executor service of Java.

    Finally here is the program for printing file names in a directory recrusively -

    import java.util.concurrent.ForkJoinPool;
    import java.util.concurrent.RecursiveAction;
    import java.util.concurrent.TimeUnit;
    public class PrintingFilesRecursivelyInDirectory {
    	private static class FilesPrinter extends RecursiveAction {
    		private static final long serialVersionUID = 1L;
    		private File directory;
    		public FilesPrinter(File directory) { = directory;
    		protected void compute() {
    			for(File file : directory.listFiles()) {
    				if(file.isDirectory()) {
    					new FilesPrinter(file).fork();
    				} else {
    	public static void main(String[] args) throws InterruptedException {
    		final ForkJoinPool forkJoinPool = ForkJoinPool.commonPool();
    		forkJoinPool.execute(new FilesPrinter(new File("C:\\Tutorials")));
    		forkJoinPool.awaitTermination(10, TimeUnit.SECONDS);




    Thank you for reading through the tutorial. In case of any feedback/questions/concerns, you can communicate same to us through your comments and we shall get back to you as soon as possible.

    Published on: 19th January 2019

    Comment Form is loading comments...