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
file - Iterating through a directory in java - Stack Overflow
I was wondering how I can make ... and perform the same operation on it. Thanks! ... It's been a while since I've done file operations, but I believe there is a way to set the filePath that you are working in (instead of the default directory). Then it would just be a matter of iterating through everything at that location. I'll look to see if I can find helpful javadocs... 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, ...
๐ŸŒ
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, ...
๐ŸŒ
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() ...
๐ŸŒ
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') } }
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.
๐ŸŒ
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 ...
๐ŸŒ
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:
๐ŸŒ
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.
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();
        }

    }
Top answer
1 of 3
3

Iโ€™m not 100% solid on how JAD works exactly, but based on the info I found in this README file, this find command should give you a start:

find . -type f -name '*.class' |\
  while IFS= read -r java_class_path
  do
    java_dirname=$(dirname "${java_class_path}")
    jad -sjava -d"${java_dirname}" "${java_class_path}"
  done

The -s option will set the output extension to .java and the -d sets a destination directory for file output based on where the original .class file was found via find. The key to solving problems like this is to understand you are not the first person who wanted to output command line output to another destination.

2 of 3
1

jad has support for this built-in, according to the documentation. It will expand globs for you, including ** recursive globs. So use quotes to protect them from the shell, like this example cmd copied from the docs:

jad -o -r -sjava -dsrc 'tree/**/*.class'

This command decompiles all .class files located in all subdirectories of tree and creates output files in subdirectories of src according to package names of classes. For example, if file tree/a/b/c.class contains class c from package a.b, then output file will have a name src/a/b/c.java.

This is almost certainly the best option if you like its choices of directory structure. I looks like without -r it won't turn package structure into directories. IDK if you could get it to put the .java files next to the the .class files with your directory structure.


Using find -execdir to run jad in the right directory:

# untested
find [more find options]  -name '*.class' -execdir jad {} +

This will effectively cd to every directory that contains at least one .class, and do the equivalent of running jad *.class there. (Note the + instead of \; to group multiple args into one command).

GNU find is powerful; read the man page.


Or use bash features:

Since you're using bash, you can make for dir in ./* recursive with bash's globstar feature. It's significantly slower than find for big directory trees, because it bash doesn't know to take advantage of the file-type hint returned by readdir to avoid having to lstat every dir entry to see if it's a directory. But bash recursive globs can be useful.

# untested
shopt -s globstar       # put this in your .bashrc if you want it enabled all the time

for dir in ./**/; do
    pushd "$dir"
    classfiles=( *.class )               # expand the glob into an array
    [[ -e $classfiles ]] &&              # test the first element of the array.  Will fail if *.class didn't match anything.
       jad *.class
    popd "$dir"
done

Note the use of a trailing slash to make the glob match only directories.

๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ java-program-to-list-all-files-in-a-directory-and-nested-sub-directories
Java Program to List all Files in a Directory and Nested Sub-Directories - GeeksforGeeks
July 23, 2025 - Here we use recursion only for nested sub-directories. For main directory files, we use foreach loop. ... // Recursive Java program to print all files // in a folder(and sub-folders) import java.io.File; public class GFG { static void ...