Recursively List All File Paths in a Java Project Directory
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.