I tested the solution with the most bursts written by @ tan70, however it caused a null pointer exception when printing my home directory. I did some research and found that listFiles () can return zero.
open file [] listFiles ()
Returns an array of abstract paths denoting files in the directory indicated by this abstract path.
If this abstract path does not indicate a directory, then this method returns zero . Otherwise, an array of File objects is returned, one for each file or directory in the directory.
public static String printDirectoryTree(String path) { File folder = new File(path); if (!folder.isDirectory()) { throw new IllegalArgumentException("folder is not a Directory"); } int indent = 0; StringBuilder sb = new StringBuilder(); printDirectoryTree(folder, indent, sb); return sb.toString(); } private static void printDirectoryTree(File folder, int indent, StringBuilder sb) { if (folder != null && folder.isDirectory() && folder.listFiles() != null) { sb.append(getIndentString(indent)); sb.append("+--"); sb.append(folder.getName()); sb.append("/"); sb.append("\n"); for (File file : folder.listFiles()) { if (file.isDirectory()) { printDirectoryTree(file, indent + 1, sb); } else { printFile(file, indent + 1, sb); } } } } private static void printFile(File file, int indent, StringBuilder sb) { sb.append(getIndentString(indent)); sb.append("+--"); if (file != null) { sb.append(file.getName()); } else { sb.append("null file name"); } sb.append("\n"); } private static String getIndentString(int indent) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < indent; i++) { sb.append("| "); } return sb.toString(); }
source share