You can use File#isDirectory() to test if the given file (path) is a directory. If this is true, then you just call the same method again with its File#listFiles() outcome. This is called recursion.

Here's a basic kickoff example:

package com.stackoverflow.q3154488;

import java.io.File;

public class Demo {

    public static void main(String... args) {
        File dir = new File("/path/to/dir");
        showFiles(dir.listFiles());
    }

    public static void showFiles(File[] files) {
        for (File file : files) {
            if (file.isDirectory()) {
                System.out.println("Directory: " + file.getAbsolutePath());
                showFiles(file.listFiles()); // Calls same method again.
            } else {
                System.out.println("File: " + file.getAbsolutePath());
            }
        }
    }
}

Note that this is sensitive to StackOverflowError when the tree is deeper than the JVM's stack can hold. If you're already on Java 8 or newer, then you'd better use Files#walk() instead which utilizes tail recursion:

package com.stackoverflow.q3154488;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class DemoWithJava8 {

    public static void main(String... args) throws Exception {
        Path dir = Paths.get("/path/to/dir");
        Files.walk(dir).forEach(path -> showFile(path.toFile()));
    }

    public static void showFile(File file) {
        if (file.isDirectory()) {
            System.out.println("Directory: " + file.getAbsolutePath());
        } else {
            System.out.println("File: " + file.getAbsolutePath());
        }
    }
}
Answer from BalusC on Stack Overflow
Top answer
1 of 11
251

You can use File#isDirectory() to test if the given file (path) is a directory. If this is true, then you just call the same method again with its File#listFiles() outcome. This is called recursion.

Here's a basic kickoff example:

package com.stackoverflow.q3154488;

import java.io.File;

public class Demo {

    public static void main(String... args) {
        File dir = new File("/path/to/dir");
        showFiles(dir.listFiles());
    }

    public static void showFiles(File[] files) {
        for (File file : files) {
            if (file.isDirectory()) {
                System.out.println("Directory: " + file.getAbsolutePath());
                showFiles(file.listFiles()); // Calls same method again.
            } else {
                System.out.println("File: " + file.getAbsolutePath());
            }
        }
    }
}

Note that this is sensitive to StackOverflowError when the tree is deeper than the JVM's stack can hold. If you're already on Java 8 or newer, then you'd better use Files#walk() instead which utilizes tail recursion:

package com.stackoverflow.q3154488;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class DemoWithJava8 {

    public static void main(String... args) throws Exception {
        Path dir = Paths.get("/path/to/dir");
        Files.walk(dir).forEach(path -> showFile(path.toFile()));
    }

    public static void showFile(File file) {
        if (file.isDirectory()) {
            System.out.println("Directory: " + file.getAbsolutePath());
        } else {
            System.out.println("File: " + file.getAbsolutePath());
        }
    }
}
2 of 11
101

If you are using Java 1.7, you can use java.nio.file.Files.walkFileTree(...).

For example:

public class WalkFileTreeExample {

  public static void main(String[] args) {
    Path p = Paths.get("/usr");
    FileVisitor<Path> fv = new SimpleFileVisitor<Path>() {
      @Override
      public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
          throws IOException {
        System.out.println(file);
        return FileVisitResult.CONTINUE;
      }
    };

    try {
      Files.walkFileTree(p, fv);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

}

If you are using Java 8, you can use the stream interface with java.nio.file.Files.walk(...):

public class WalkFileTreeExample {

  public static void main(String[] args) {
    try (Stream<Path> paths = Files.walk(Paths.get("/usr"))) {
      paths.forEach(System.out::println);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

}
🌐
Attacomsian
attacomsian.com › blog › java-traverse-directory-structure
How to traverse a directory structure in Java
December 15, 2019 - In Java 8 and higher, you can use the Files.walk() method from Java NIO API to iterate through all files and sub-directories in a particular directory as shown below:
Discussions

List and iterate over sub-directories
How do I get a list of sub directories at the specified path, and iterate over it ! // Prompt for target directory def dirExports = Dialogs.promptForDirectory() if (dirExports == null) return //get list of subdirectories def subDirs = [] for dir in dirExports.listDirectories(){ //process routine ... More on forum.image.sc
🌐 forum.image.sc
13
0
August 17, 2020
How to iterate over the files of a certain directory, in Java? - Stack Overflow
Possible Duplicate: Best way to iterate through a directory in java? I want to process each file in a certain directory using Java. What is the easiest (and most common) way of doing this? More on stackoverflow.com
🌐 stackoverflow.com
loops - Java Basics - Looping through folder - Stack Overflow
I am very new to java and coming from a js background. I am attempting to loop through a folder full of files and zipping it. Currently, I have done the zipping part successfully, but doing by stat... More on stackoverflow.com
🌐 stackoverflow.com
How to loop through a directory, get all file names, then get the contents of those files in Java - Stack Overflow
So in C drive, I have a folder called Search Files and inside Search Files, I have four subdirectories called Folder 1, Folder 2, Folder 3, and Folder 4. Inside of Folder 1, I have a text file called More on stackoverflow.com
🌐 stackoverflow.com
🌐
Quickprogrammingtips
quickprogrammingtips.com › java › how-to-iterate-through-a-directory-tree-in-java.html
How to Iterate Through a Directory Tree in Java
The following example Java program iterates through all the files and directories in a given folder. It also walks through the entire directory tree printing names of sub-directories and files. Note that this example requires Java 8 or above since it uses java.nio.file.Files class and the walk ...
🌐
Learn IT University
learn-it-university.com › home › mastering file navigation in java: a guide to iterating through directories and sub-directories
Mastering File Navigation in Java: A Guide to Iterating Through Directories and Sub-Directories - Learn IT University
July 21, 2024 - In Java, iterating through files in a directory and its subdirectories can be achieved using both traditional recursion and modern features provided by the NIO package. Understanding these methods is essential for tasks like file management, ...
🌐
Coopcie
coopcie.it › java-loop-through-directory-and-sub-directories.html
Java loop through directory and sub directories
FOR /D %y IN (D:\movie\*) DO @ECHO %y. Now this will go through even the sub-directories inside movie folder if there exist any. So, this is all about the batch file for loops. ... If an application is present in a directory that isn't set in environment variable PATH, then you can specify ...
🌐
Fadeawayitalia
fadeawayitalia.it › java-loop-through-directory-and-sub-directories.html
Java loop through directory and sub directories
Nov 14, 2018 · How to figure out if a path (the function outputs all possible paths, thats what i understood) is not directory with sub directories, but a directory with images or text files, so I can process them. After choosing a path, I need to figure out how to loop through files. Jul 14, 2019 · Extract Zip File With Subdirectories Using Command Line Argument Example. This Java example shows how to extract a zip file and create required sub-directories using Java ZipInputStream class.
🌐
JavaMadeSoEasy
javamadesoeasy.com › 2015 › 08 › program-to-traverse-directory-all-sub.html
JavaMadeSoEasy.com (JMSE): Program to Traverse a Directory (all sub-directories and files) in 2 ways | using org.apache.commons.io.FileUtils in java file IO
org.apache.commons.io.FileUtils's iterateFiles(dir, null, false) method can be used to iterate over all files in directory and its sub-directories ... Note : In order to avoid java.io.FileNotFoundException you must use java.io.File's isDirectory() ...
Find elsewhere
🌐
javathinking
javathinking.com › blog › how-do-i-iterate-through-the-files-in-a-directory-and-it-s-sub-directories-in-java
How to Iterate Through Files in a Directory and Subdirectories in Java: The Standard Method Explained — javathinking.com
In this blog, we’ll explore the standard method for iterating through files in directories and subdirectories using Java’s NIO.2 API. We’ll cover both non-recursive (single directory) and recursive (subdirectories included) iteration, with practical examples, exception handling, and best practices.
🌐
Image.sc
forum.image.sc › usage & issues
List and iterate over sub-directories - Usage & Issues - Image.sc Forum
August 17, 2020 - How do I get a list of sub directories at the specified path, and iterate over it ! // Prompt for target directory def dirExports = Dialogs.promptForDirectory() if (dirExports == null) return //get list of subdirectories def subDirs = [] for dir in dirExports.listDirectories(){ //process routine goes here print(directory + ' processed') } }
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-program-to-traverse-in-a-directory
Java Program to Traverse in a Directory - GeeksforGeeks
July 23, 2025 - Java 8 onwards, the walk() method was introduced to iterate over the entire directory recursively and retrieve Stream<Path> as the return value. ... Create a stream of file paths. Print entire directory and file path.
🌐
HowToDoInJava
howtodoinjava.com › home › java 8 › listing all files in a directory in java
Listing All Files in a Directory in Java
October 1, 2022 - For using external iteration (for loop) use DirectoryStream. For using Stream API operations, use Files.list() instead. If we are interested in non-recursively listing the files and excluding all sub-directories and files in sub-directories, ...
🌐
ZetCode
zetcode.com › java › directorystream
Java DirectoryStream - iterating over directories with DirectoryStream
This approach is efficient and well-suited for processing directory contents without loading everything into memory at once. A DirectoryStream provides a flexible way to traverse the entries in a directory. It integrates seamlessly with the enhanced for-loop, allowing developers to iterate ...
🌐
Example Code
example-code.com › java › dirTree_iterate.asp
Java Iterate over Files and Directories in Filesystem Directory Tree
Chilkat • HOME • Android™ • AutoIt • C • C# • C++ • Chilkat2-Python • CkPython • Classic ASP • DataFlex • Delphi DLL • Go • Java • Node.js • Objective-C • PHP Extension • Perl • PowerBuilder • PowerShell • PureBasic • Ruby • SQL Server • Swift • Tcl • Unicode C • ...
🌐
TechRepublic
techrepublic.com › home › developer
Directory Navigation in Java - TechRepublic
July 15, 2023 - Directory: AAMS Directory: Addictive Drums Directory: Angular Directory: angular-starter Directory: Any Video Converter Directory: articles File: Avatar - House Of Eternal Hunt - transposed.tg File: Avatar - House Of Eternal Hunt.tg File: Avatar - Legend Of The King.tg Directory: bgfx · Since we can test for directories, we can move our for loop into a separate method that we can invoke recursively to list the files of subdirectories as well as the one provided to our method, as shown in the follow Java code example:
Top answer
1 of 2
1

The answer is in this article: http://www.baeldung.com/java-compress-and-uncompress

This code zips multiple files (Very similar to your code but slightly changed):

public class ZipMultipleFiles {
    public static void main(String[] args) throws IOException {
        List<String> srcFiles = Arrays.asList("test1.txt", "test2.txt");
        FileOutputStream fos = new FileOutputStream("multiCompressed.zip");
        ZipOutputStream zipOut = new ZipOutputStream(fos);
        for (String srcFile : srcFiles) {
            File fileToZip = new File(srcFile);
            FileInputStream fis = new FileInputStream(fileToZip);
            ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
            zipOut.putNextEntry(zipEntry);

            byte[] bytes = new byte[1024];
            int length;
            while((length = fis.read(bytes)) >= 0) {
                zipOut.write(bytes, 0, length);
            }
            fis.close();
        }
        zipOut.close();
        fos.close();
    }
}

EDIT: This line in the code creates an array that is easy to go through in a while loop: List<String> srcFiles = Arrays.asList("test1.txt", "test2.txt");

2 of 2
0

basically used finding children of a folder method thanks to Elliotk link. I am making the string equal to the path of the parent folder - >checking if whether if its a directory - > list its files -> get the names and while loop to write all of them to a zipped folder

here is my whole code

    package zipfolder2;

    import java.io.*;
    import java.util.*;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipOutputStream;

    public class zipfolders2 {

        public static void main(String[] args) {
            try {

                String sourceFile = "src/resources";
                FileOutputStream fos = new FileOutputStream("zippedfiles.zip");
                ZipOutputStream zipOut = new ZipOutputStream(fos);
                File fileToZip = new File(sourceFile);

                zipFile(fileToZip, fileToZip.getName(), zipOut);
                zipOut.close();
                fos.close();

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        private static void zipFile(File fileToZip, String fileName, ZipOutputStream zipOut) throws IOException {
            if (fileToZip.isHidden()) {
                return;
            }
            if (fileToZip.isDirectory()) {
                File[] children = fileToZip.listFiles();
                for (File childFile : children) {
                    zipFile(childFile, fileName + "/" + childFile.getName(), zipOut);
                }
                return;
            }
            FileInputStream fis = new FileInputStream(fileToZip);
            ZipEntry zipEntry = new ZipEntry(fileName);
            zipOut.putNextEntry(zipEntry);
            byte[] bytes = new byte[1024];
            int length;
            while ((length = fis.read(bytes)) >= 0) {
                zipOut.write(bytes, 0, length);
            }
            fis.close();
        }

    }
🌐
Medium
medium.com › @AlexanderObregon › javas-files-walk-method-explained-570d8a67247d
Java’s Files.walk() Method Explained | Medium
September 3, 2024 - In some cases, you may not want to traverse an entire directory tree but rather limit the depth of exploration. The Files.walk() method allows you to specify a maximum depth, ensuring that deeper directories are ignored.