i used this code for list all folders...
public static void main(String[] args) throws Exception {
File root = new File("C:\\Users\\resti\\Desktop\\example");
if (!root.isDirectory())
{
System.out.println("some_text");
}
int level = 0;
System.out.println(renderFolder(root, level, new StringBuilder(), false, new ArrayList<>()));
}
private static StringBuilder renderFolder(File folder, int level, StringBuilder sb, boolean isLast, List<Boolean> hierarchyTree) {
indent(sb, level, isLast, hierarchyTree).append(folder.getName()).append("\n");
File[] objects = folder.listFiles(new FilenameFilter() {
@Override
public boolean accept(File current, String name) {
return new File(current, name).isDirectory();
}
});
for (int i = 0; i < objects.length; i++) {
boolean last = ((i + 1) == objects.length);
// this means if the current folder will still need to print subfolders at this level, if yes, then we need to continue print |
hierarchyTree.add(i != objects.length - 1);
renderFolder(objects[i], level + 1, sb, last, hierarchyTree);
// pop the last value as we return from a lower level to a higher level
hierarchyTree.remove(hierarchyTree.size() - 1);
}
return sb;
}
private static StringBuilder indent(StringBuilder sb, int level, boolean isLast, List<Boolean> hierarchyTree) {
String indentContent = "\u2502 ";
for (int i = 0; i < hierarchyTree.size() - 1; ++i) {
// determines if we need to print | at this level to show the tree structure
// i.e. if this folder has a sibling foler that is going to be printed later
if (hierarchyTree.get(i)) {
sb.append(indentContent);
} else {
sb.append(" "); // otherwise print empty space
}
}
if (level > 0) {
sb.append(isLast
? "\u2514\u2500\u2500"
: "\u251c\u2500\u2500");
}
return sb;
}
}
it works and its cool but the problem is that it doesnt count normal Files like .txt or .png... i know its writen inside this method but idk how to fix it without destroing everything else
File[] objects = folder.listFiles(new FilenameFilter() {
@Override
public boolean accept(File current, String name) {
return new File(current, name).isDirectory();
}
});
can i remake the method or somethink else ?? (this code is not mine https://stackoverflow.com/a/33438475/13547682 )