Skip to content

Instantly share code, notes, and snippets.

@durgeshgowdac
Forked from LeoPFreitas/FindDeepestFile.java
Last active December 27, 2023 09:16
Show Gist options
  • Save durgeshgowdac/edb58670bd65ef45742e9ee522d5ea99 to your computer and use it in GitHub Desktop.
Save durgeshgowdac/edb58670bd65ef45742e9ee522d5ea99 to your computer and use it in GitHub Desktop.
Find the deepest file in a system file tree.
import java.io.File;
import java.util.Scanner;
class Main {
static int maxLevel = 0;
static String deepestFileName = null;
static int currentLevel = 0;
static String deepestPath = null;
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
System.out.print("Enter the absolute path of the folder: ");
File file = new File(sc.next());
goRecursive(file);
System.out.printf("\nFile Name: %s\nAbsolute Path: %s\nLevel from input directory: %d", deepestFileName,
deepestPath, maxLevel);
}
public static void goRecursive(File dir) {
if (currentLevel > maxLevel) {
deepestFileName = dir.getName();
deepestPath = dir.getAbsolutePath();
}
if (dir.isDirectory() && dir.listFiles().length != 0) {
++currentLevel;
for (File subdir : dir.listFiles()) {
goRecursive(subdir);
}
maxLevel = Math.max(maxLevel, currentLevel);
--currentLevel;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment