There is a task:

Request the path to the folder from the console, get a list of all folders of the specified folder, taking into account the hierarchy.

For example, a search in the "book" folder will give 5 items:

-book --directory1 ---file1 ---file2 --directory2 ---directory3 ----directory4 -----directory5 ------file3 

A partial implementation looks like this:

 public static void main(String[] args) { String scan = new Scanner(System.in).nextLine(); System.out.println(scan); File dir = new File(String.valueOf(scan)); if ( dir.isDirectory() ) { File[] files = dir.listFiles(); for ( File tmpFile : files ) { System.out.println("-" + tmpFile.getName()); if ( tmpFile.isDirectory() ) { File[] tmpFile1 = tmpFile.listFiles(); for ( File file3 : tmpFile1 ) { System.out.println("--" + file3.getName()); } } } } } 

Result:

 d://book -directory1 --file1.txt --file2.txt -directory2 --directory3 

The result gives the data only to the third directory, and I'll never know how to fix the code and complete the task.

    3 answers 3

    Instead of recursion, you can use the stack:

     private static class Element { public final String indent; public final File file; public Element(String indent, File file) { this.indent = indent; this.file = file; } public String toString() { return indent + file.getName(); } } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String path = scanner.nextLine(); File dir = new File(path); if (!dir.exists() || !dir.isDirectory()) { System.out.println("Incorrect directory name"); } Deque<Element> stack = new ArrayDeque<>(); stack.add(new Element("-", dir)); while (!stack.isEmpty()) { Element element = stack.pollLast(); System.out.println(element); if (element.file.isDirectory()) { File[] files = element.file.listFiles(); for (int i = files.length - 1; i >=0; i--) { stack.add(new Element(element.indent + "-", files[i])); } } } } 

    The idea remains the same: we take the next file / directory, display it, and then, if it is a directory, add the contents of this folder to the processing. And so on until there is something to handle.

    • one
      Great idea to use the stack) everything turned out the best. Thank you) - Diana Meissen

    The standard library has a great class Files , it has a static method walkFileTree . He is needed precisely for what you want. Those. to traverse the directory tree.

    The code will be as follows:

     Path parent = Paths.get("<корневая директория>"); Files.walkFileTree(parent, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { int count = dir.getNameCount() - parent.getNameCount() + 1; count += dir.getFileName().toString().length(); //выравнивание по правому краю String text = String.format("%" + count + "s", dir.getFileName()); text = text.replaceAll("[\\s]", "-"); System.out.println(text); return FileVisitResult.CONTINUE; } }); 

      Do not believe it, I broke my head for half an hour and could not come up with a solution without recursion. Here is the code that I got

       public class Main { static String counter = "-"; public static void main(String[] args) { System.out.println("Путь к папке"); Scanner s = new Scanner(System.in); String path = s.nextLine(); File dir = new File(path); if(!dir.exists()){ System.out.println("Папки с введеным именем не существует"); } else if(!dir.isDirectory()){ System.out.println("Не является папкой"); } else { printAllFilesFromDirectory(dir); } } static void printAllFilesFromDirectory(File dir){ for(File file : dir.listFiles()) { print(file); if(file.isDirectory()) { counter += "-"; printAllFilesFromDirectory(file); } } counter -= "-"; } static void print(File file){ System.out.println(counter + " " + file.getName()); } } 

      After fool checks, the input path is passed to the printAllFilesFromDirectory method. In it, each file is passed to the print() method, in which the dash and its name are displayed. The number of dashes is determined by the counter counter (its default value is one). After the print method, if the file is a directory, we increment the counter as the hierarchy level has increased. After that, we execute the method using recursion and pass it the directory.

      As a result, this method will output all files and directories with respect to the hierarchy. Pay attention to the decrement counter . It happens when all files are output! (Directories are not, in this case recursion occurs)

      Yes, I know, if the path is too long, then the recursion will cause a stack overflow. I repeat: I could not come up with another solution :)

      UPDATE

      Now counter is a string (the print method looked ugly.