Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Recursively List All File Paths in a Java Project Directory

Tech 1

To rterieve all file paths within a Java project during runtime—assuming the project is running from an unpacked directory—you can use recursive file traversal starting from the classpath root.

import java.io.File;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class FilePathCollector {

    public static void main(String[] args) {
        List<String> filePaths = new ArrayList<>();
        try {
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            URL resourceUrl = loader.getResource("");

            if ("file".equals(resourceUrl.getProtocol())) {
                String decodedPath = URLDecoder.decode(
                    resourceUrl.getFile(), 
                    StandardCharsets.UTF_8.toString()
                );
                File rootDir = new File(decodedPath);
                collectFiles(rootDir, filePaths);
            }

            filePaths.forEach(System.out::println);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private static void collectFiles(File dirOrFile, List<String> paths) {
        if (dirOrFile.isDirectory()) {
            File[] children = dirOrFile.listFiles();
            if (children != null) {
                for (File child : children) {
                    collectFiles(child, paths);
                }
            }
        } else {
            paths.add(dirOrFile.getAbsolutePath());
        }
    }
}

This approach works only when the application runs from a file system directory (e.g., during development or exploded deployment). It does not support scannign files packaged inside JARs or other archive formats. Performance may degrade with very large directory trees due to deep recursion and I/O overhead.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.