How to find the wood of the folder of the inner folder
-
I'm doing a code to build a tree from the files and files. Initially, my code gets something, and if it's empty.
if (!file.exists())
returns emptyString
if there's a file that returns the name of the file.public Optional<String> tree(Path path) {
File file = new File(String.valueOf(path)); if (!file.exists()) { return Optional.empty(); } else if (file.isFile()) { return Optional.of(file.getName()); } else if (file.isDirectory()) { ... } return null; }
Difficulties start when there's a file. In this case, I have to see what's in it and if there's a file to see what's in it and so on. Trying to do it with help.
if-else
but this design works only to the level of the design.if-else
and I need to keep it out of line, and the program gives the whole chick's results.else if (file.isDirectory()) {
System.out.println(file.getName());File[] filesArray = file.listFiles(); for (File filer : filesArray) { if (filer.isFile()) { System.out.println(filer.getName()); } else if (filer.isDirectory()) { System.out.println(filer.getName()); File[] filesArrays = filer.listFiles(); for (File filers : filesArrays) { if (filers.isFile()) { System.out.println(filers.getName()); } } } else { System.out.println(filer.getName()); }
In this design, the result has been obtained, but if there is a folder inner 1.1 in the file, the same result will be:
test1
inner1
some.txt
some1.txt
some.txt
some1.txt
some2.txt
-
See if you can use a lesson for this purpose:
void printRecursiveTree(Path path) { File file = new File(String.valueOf(path)); if (file.isFile()) { System.out.println(file.getName()); } else if (file.isDirectory()) { File[] filesArray = file.listFiles(); for (File filer : filesArray) { printRecursiveTree(filer.toPath()); } } }
A small bonus, you can make a tree of files more realistic by taking off:
void printRecursiveTree(Path path, int level) { File file = new File(String.valueOf(path)); if (file.isFile()) { System.out.println(" ".repeat(level) + file.getName()); } else if (file.isDirectory()) { File[] filesArray = file.listFiles(); for (File nestedFile : filesArray) { printRecursiveTree(nestedFile.toPath(), level + 1); } } }
Purpose:
printRecursiveTree(Path.of("C:/Users/oQaris/Desktop/Git"), 0);