If you have the directory name in myDirectoryPath,

import java.io.File;
...
  File dir = new File(myDirectoryPath);
  File[] directoryListing = dir.listFiles();
  if (directoryListing != null) {
    for (File child : directoryListing) {
      // Do something with child
    }
  } else {
    // Handle the case where dir is not really a directory.
    // Checking dir.isDirectory() above would not be sufficient
    // to avoid race conditions with another process that deletes
    // directories.
  }
Answer from Mike Samuel 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();
    }
  }

}
🌐
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 - Learn to use various Java APIs such as Files.list() and DirectoryStream to list all files present in a directory, including hidden files, recursively. For using external iteration (for loop) use DirectoryStream.
🌐
Java Code Geeks
examples.javacodegeeks.com › home › java development › core java › nio
Java Nio Iterate Over Files in Directory - Java Code Geeks
March 12, 2019 - This will mean it will include file creation and modification time stamps and file / directory sizes. java -jar iterate-directory-0.0.1-SNAPSHOT.jar -r /home/user/temp -v -f Test this will list all the directories contained within /home/user/temp in verbose mode.
🌐
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 ...
🌐
Coderanch
coderanch.com › t › 381939 › java › iterate-files-directory
how to iterate over files in a directory (Java in General forum at Coderanch)
January 30, 2007 - Ask Java to list files in the directory, using your FileFilter. Every time Java calls your FileFilter, append a line containing the leaf name to the temporary file. Return false, so Java returns you no files. Then iterate through the contents of the temporary file.
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-program-to-traverse-in-a-directory
Java Program to Traverse in a Directory - GeeksforGeeks
July 23, 2025 - The following image displays the files and directories present inside GFG folder. The subdirectory "Ritik" contains a file named "Logistics.xlsx" and the subdirectory "Rohan" contains a file named "Payments.xlsx". ... Create a File array to store the name and path of files. Call displayFiles method() to display all the files. ... // Java Program to Traverse Through a Directory // Importing required classes import java.io.File; // Main class class GFG { // Method 1 // To display files public static void displayFiles(File[] files) { // Traversing through the files array for (File filename : file
Find elsewhere
🌐
Coderanch
coderanch.com › t › 638517 › java › Iterate-string-file-paths-directory
Iterate through a string of file paths in a directory (Java in General forum at Coderanch)
August 24, 2014 - If so, you would generally use File.listFiles and a for() loop. ... I have a FileNameFilter that searches a directory for all files with the ".PAT" extension. This returns a list of file paths like so: M:\\directory\\file1.PAT M:\\directory\\file2.PAT M:\\directory\\file3.PAT I then have a FileInputStream within a BufferedReader that will read the file path and process the file accordingly. I am trying to figure out the best way to iterate through the file paths, process the files into a new text file, then move onto the next file path.
🌐
Attacomsian
attacomsian.com › blog › java-traverse-directory-structure
How to traverse a directory structure in Java
December 15, 2019 - In Java 7 or below, you can write a recursive function to traverse all files and folders in a given directory: public static void traverseDir(File dir) { File[] files = dir.listFiles(); if(files != null) { for (final File file : files) { ...
🌐
TechRepublic
techrepublic.com › home › developer
Directory Navigation in Java - TechRepublic
July 15, 2023 - This programming tutorial will demonstrate how to utilize each of the above techniques to navigate a directory structure in Java. SEE: Top Java IDEs · Contents · The File listFiles() method in Java · Using DirectoryStream to loop through files with Java ·
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();
        }

    }
🌐
TutorialsPoint
tutorialspoint.com › java-program-to-traverse-in-a-directory
Java Examples - Traversing Directory
Following example demonstratres how to traverse a directory with the help of dir.isDirectory() and dir.list() methods of File class. import java.io.File; public class Main { public static void main(String[] argv) throws Exception { System.out.println("The Directory is traversed."); visitAllDirsAndFiles(C://Java); } public static void visitAllDirsAndFiles(File dir) { System.out.println(dir); if (dir.isDirectory()) { String[] children = dir.list(); for (int i = 0; i < children.length; i++) { visitAllDirsAndFiles(new File(dir, children[i])); } } } }