How to scan a folder in Java?

How can I get list all the files within a folder recursively in Java?

Asked by: John485 | Posted: 23-01-2022

Answer 1

Not sure how you want to represent the tree? Anyway here's an example which scans the entire subtree using recursion. Files and directories are treated alike. Note that File.listFiles() returns null for non-directories.

public static void main(String[] args) {
    Collection<File> all = new ArrayList<File>();
    addTree(new File("."), all);

static void addTree(File file, Collection<File> all) {
    File[] children = file.listFiles();
    if (children != null) {
        for (File child : children) {
            addTree(child, all);

Java 7 offers a couple of improvements. For example, DirectoryStream provides one result at a time - the caller no longer has to wait for all I/O operations to complete before acting. This allows incremental GUI updates, early cancellation, etc.

static void addTree(Path directory, Collection<Path> all)
        throws IOException {
    try (DirectoryStream<Path> ds = Files.newDirectoryStream(directory)) {
        for (Path child : ds) {
            if (Files.isDirectory(child)) {
                addTree(child, all);

Note that the dreaded null return value has been replaced by IOException.

Java 7 also offers a tree walker:

static void addTree(Path directory, final Collection<Path> all)
        throws IOException {
    Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                throws IOException {
            return FileVisitResult.CONTINUE;

Answered by: Brooke510 | Posted: 24-02-2022

Answer 2

public class Test {
    public static void main( String [] args ) {
        File actual = new File(".");
        for( File f : actual.listFiles()){
            System.out.println( f.getName() );

It displays indistinctly files and folders.

See the methods in File class to order them or avoid directory print etc.

Answered by: Lyndon792 | Posted: 24-02-2022

Answer 3

You can also use the FileFilter interface to filter out what you want. It is best used when you create an anonymous class that implements it:


public class ListFiles {
    public File[] findDirectories(File root) { 
        return root.listFiles(new FileFilter() {
            public boolean accept(File f) {
                return f.isDirectory();

    public File[] findFiles(File root) {
        return root.listFiles(new FileFilter() {
            public boolean accept(File f) {
                return f.isFile();

Answered by: Blake192 | Posted: 24-02-2022

Answer 4

public static void directory(File dir) {
    File[] files = dir.listFiles();
    for (File file : files) {
        if (file.listFiles() != null)

Here dir is Directory to be scanned. e.g. c:\

Answered by: Ryan415 | Posted: 24-02-2022

Answer 5

Visualizing the tree structure was the most convenient way for me :

public static void main(String[] args) throws IOException {
    printTree(0, new File("START/FROM/DIR"));

static void printTree(int depth, File file) throws IOException { 
    StringBuilder indent = new StringBuilder();
    String name = file.getName();

    for (int i = 0; i < depth; i++) {

    //Pretty print for directories
    if (file.isDirectory()) { 
        System.out.println(indent.toString() + "|");
            System.out.println(indent.toString() + "*" + file.getName() + "*");
    //Print file name
    else if(isPrintName(name)) {
        System.out.println(indent.toString() + file.getName()); 
    //Recurse children
    if (file.isDirectory()) { 
        File[] files = file.listFiles(); 
        for (int i = 0; i < files.length; i++){
            printTree(depth + 4, files[i]);

//Exclude some file names
static boolean isPrintName(String name){
    if (name.charAt(0) == '.') {
        return false;
    if (name.contains("svn")) {
        return false;
    //. Some more exclusions
    return true;

Answered by: Emily681 | Posted: 24-02-2022

Answer 6

In JDK7, "more NIO features" should have methods to apply the visitor pattern over a file tree or just the immediate contents of a directory - no need to find all the files in a potentially huge directory before iterating over them.

Answered by: Agata622 | Posted: 24-02-2022

Similar questions

java - What makes a file into a folder?

java - Make jar file from folder

i have a folder on my desktop named theme.I am new to Linux totally. So what do I do to create a jar file from this folder? I found this example but It doesn't work for me. jar -cvf theme.jar

File not found in same folder Java

I am trying to read a file in Java. I wrote a program and saved the file in the exact same folder as my program. Yet, I keep getting a FileNotFoundException. Here is the code: public static void main(String[] args) throws IOException { Hashtable&lt;String, Integer&gt; ht = new Hashtable&lt;String, Integer&gt;(); File f = new File("file.txt"); ArrayList&lt;String&gt; al = readFile(f,...

java - How can I get a file that might be under the src folder and might be in the jar?

I have a resource file I need to read from my code. So when I'm developing it's under the src folder (and copied under the classes folder). When we're in production it's in the jar file. How can I set an absolutely qualified path to the file that works for all cases? Update: Trying the following but it doesn't always work is = getResourceStream(RESOURCE_PATH + afmFile + ".afm", resourceAncho...

java - What I will do if my .jar file can not run outside the "dist" folder?

I have made a Stopwatch for my personal interest using JFrame Form in Netbeans. Then I made a .jar file. I follwed the instructions stated below. 1. Right-click on the Project name. 2. Select Properties. 3. Click Packaging. 4. Check Build JAR after Compiling. 5. Check Compress JAR File. 6. Click OK to accept changes. 7. Right-click on a Project name. 8. Select Build or Clean and Build. I f...

java - make jar file in different folder

when making jar file in java, how to make jar file in a different folder where other files are not located? I have two folders f1&amp;f2 in f1/ft1/ft2/ft3 I have the java code in f2/ft1 I have few csv fine files to be used in the java code, and I have to create jar in f2/ft2. how to do it?

java - how to run the batch file from any folder

cd ../../jobs set CLASSPATH=.;../xyz.jar;../mysql-connector-java-5.1.6-bin.jar java folser.folder1 ../Files/MySQL.xml cd .. I need to run the batch file from any directory. I have set the paths for java. Can anybody help me?

java - Why can't I access a file within my jar unless I'm in the folder with the Jar when I run it?

I recently created an application and successfully jarred this to c:/my/folder/app.jar. It works like a charm in the following case [Startup #1]: Open cmd cd to c:/my/folder java -jar app.jar But when I do this, it doesn't work [Startup #2]: Open cmd cd to c:/my/ java -jar folder/app.jar Because app.jar contains a .exe-file which ...

io - How to make a folder hidden using java

I want to create a hidden folder using java application. That program should work across platform. So How to write a program which can create hidden folder. I have tried using File newFile = new File("myfile"); newFile.mkdir(); It creates a directory which is not hidden.

Add a folder having files into a zip file using JAVA

I am using java's api to add files and folders to a zip file, but when i add multiple files into the same folder, it deleted the old contents. Is there any way i can add files into the zip file without modifying existing contents in the folder?. Kindly help, its important! This is my sample code: ZipOutputStream zip = null; FileOutputStream fileWriter = null; fileWriter = new FileOutp...

Get 48x48 icon size of any file, folder or drive in java

How to get 48x48 icon size of any file, folder or drive in java?

java - Get folder size

Do you know how can I get the folder size in Java? The length() method in the File class only works for files, using that method I always get a size of 0.

java - Share a folder in tomcat

How can I enable a folder to be accessable using a browser with tomcat 6 ? I think I need to add a context to web.xml ? I'm trying - So when I navigate to http://localhost:8080/myfiles I expect to see the contents of c:\temp Thanks

java - What is JavaMail Folder type 3?

I know that JavaMail knows the following types of IMAP folders: Folder.HOLDS_MESSAGES (which equals the constant 1) and Folder.HOLDS_FOLDERS (which equals the constant 2). So, today I did: int type = folder.getType(); on a folder called "Drafts", which should be type 2. But the variable type contains the value 3, which does not seem to be documented anywhere.

java - How to play video from sd folder

So I hope it's not a repeated question but, from the following code File f = new File(Environment.getExternalStorageDirectory(), TRYVID); Uri uri = Uri.fromFile(f); mc = new MediaController(this); mp.setMediaController(mc); mp.setVideoPath("/sdcard/try2.mp4"); this is part of a function that's called when a button is pressed, what i'm hoping to achieve is that when the user presses a ke...

Find files in a folder using Java

What I need to do if Search a folder say C:\example I then need to go through each file and check to see if it matches a few start characters so if files start temp****.txt tempONE.txt tempTWO.txt So if the file starts with temp and has an extension .txt I would like to then put that file name into a File file = new File("C:/example/temp***.txt); so I can ...

Still can't find your answer? Check out these amazing Java communities for help...

Java Reddit Community | Java Help Reddit Community | Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)