You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

组合模式实现文件系统:showAll方法无法递归显示子目录内容

解决文件系统showAll方法无法递归显示子目录的问题

问题根源

你的Directory类的showAll()方法只实现了当前目录名称和文件的输出,没有递归处理子目录,所以子目录Directory11及其下的文件不会被打印。另外File类的setName()方法存在赋值错误,会导致文件名无法修改。

解决方案

  1. 修改Directory的showAll()方法:添加递归遍历子目录的逻辑,可选增加缩进参数体现目录层级
  2. 修正File类的setName()方法:将错误的赋值语句修正为正确的this.fileName = name

修改后的关键代码

修正后的File类

public class File {
    private String fileName;

    public File(String fileName) {
        this.fileName = fileName;
    }
    public String getName() {
        return fileName;
    }
    public void setName(String name) {
        // 修正赋值错误
        this.fileName = name;
    }
}

无缩进版本的Directory类(匹配你期望的输出格式)

public class Directory {
    private String directoryName;
    private List<File> files;
    private List<Directory> subDirs;

    public Directory(String directoryName) {
        this.directoryName = directoryName;
        files = new ArrayList<File>();
        subDirs = new ArrayList<Directory>();
    }
    // 省略其他已有方法...

    public void showAll() {
        System.out.println(this.directoryName);
        for (File f : files) {
            System.out.println(f.getName());
        }
        // 递归遍历子目录
        for (Directory subDir : subDirs) {
            subDir.showAll();
        }
    }
}

运行结果

执行Create类的main方法后,输出将完全符合你的期望:

Directory1
FileX
Directory11
File1
File2

可选:带层级缩进的版本(让结构更直观)

如果希望目录层级更清晰,可以重载showAll方法添加缩进逻辑:

public class Directory {
    // 省略其他已有代码...

    public void showAll() {
        showAll(0);
    }

    private void showAll(int indentLevel) {
        String indent = "    ".repeat(indentLevel);
        System.out.println(indent + this.directoryName);
        
        for (File f : files) {
            System.out.println(indent + "    " + f.getName());
        }
        
        for (Directory subDir : subDirs) {
            subDir.showAll(indentLevel + 1);
        }
    }
}

此时输出会呈现层级结构:

Directory1
    FileX
    Directory11
        File1
        File2

内容的提问来源于stack exchange,提问作者Xavi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 19:48:23