Iterating through a directory structure in Java

Posted on 04-01-2013 07:55 by graham
In this short tutorial we will show how you can iterate through a multilevel directory structure in Java.

In fact, I think the sample code below speaks for itself :)
public void scanDir (File[] files)
for (File file : files)
if (file.isDirectory())
System.out.println("Directory: " + file.getName());
// enter next directory
scanDir (file.listFiles());
System.out.println("File: " + file.getName());

What happens is that we create a method called scanDir that iterates through all items in a given directory. It checks both folders and files, and if it discovers a directory, it calls itself resursively.


Add comment

Has this tutorial been helpful to you? Or do you see anything wrong? We appreciate your opinion!
Your comment:
Show formatting hints
HTML is disallowed, but in your text you can use the following markup
  • [code][/code] for a block of code
  • [tt][/tt] for inline code
  • [link]link href|link anchor[/link] for links
  • [b][/b] for bold text
+ Ask a question
If you have a technical question related to programming and computers, ask it here. Other users will help you solve it!
Unanswered questions
Share your knowledge by helping others solve their problems