print directory tree

前端 未结 10 1491
傲寒
傲寒 2020-12-03 08:45

I have to print a directory tree (like tree command), example:

 .
 +---A
 |   +---IMAGES
 |       +---BACKUP
 +---ADOKS
 |   +---ROZDZIAL_2
 |   +---ROZDZIAL         


        
10条回答
  •  孤街浪徒
    2020-12-03 08:55

    I was testing the solution with the most upticks written by @tan70 however it caused a null pointer exception on printing my home directory. I did some investigation and found that listFiles() can return null.

    public File[] listFiles()

    Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname.

    If this abstract pathname does not denote a directory, then this method returns null. Otherwise an array of File objects is returned, one for each file or directory in the directory

    /**
     * Pretty print the directory tree and its file names.
     *
     * @param path
     * @return
     */
    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();
    }
    

提交回复
热议问题