javacomposite

File System using composite pattern


I'm trying to build a File system such that contains the following classes: FileSystem, Directory, File.
My code is:

public class FileSystem {
    private List<Directory> ld;
    public FileSystem() {
        ld = new ArrayList<Directory>();
    }
    public void addDirectory(Directory dir) {
        ld.add(dir);
    }
    public void showAll() {
        for (Directory directory : ld) {
            directory.showAll();
        }
    }
}

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 = fileName;
    }
}

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 String getName() {
        return this.directoryName;
    }
    public void setName(String name) {
        this.directoryName = name;
    }
    // Add and remove files
    public void addFile(File file) {
        files.add(file);
    }
    public void removeFile(File file) {
        files.remove(file);
    }
    // Add and remove directories
    public void addDirectory(Directory dir) {
        subDirs.add(dir);
    }
    public void removeDirectory(Directory dir) {
        subDirs.remove(dir);
    }

    public void showAll() {
        System.out.println(this.directoryName);
        for (File f : files) {
            System.out.println("    " + f.getName());
        }
    }
}

public class Create {
    public static void main(String[] args) {
        FileSystem fs = new FileSystem();
        Directory d1 = new Directory("Directory1");

        d1.addFile(new File("FileX"));
        Directory d11 = new Directory("Directory11");
        d11.addFile(new File("File1"));
        d11.addFile(new File("File2"));
        d1.addDirectory(d11);

        fs.addDirectory(d1);
        fs.showAll();
    }
}  

But when I try to print all the content using the method showAll it prints only 'Directory1' and 'FileX', but I want to print:
Directory1
FileX
Directory11
File1
File2


Solution

  • Your Directory#showAll should look like this:

    public void showAll() {
        System.out.println(this.directoryName);
        for (File f : files) {
            System.out.println("    " + f.getName());
        }
        for(Directory subDir: subDirs){
            subDir.showAll();
        }
    }
    

    So it traverses recursively through subDirs also.

    P.S. - I would also get rid of FileSystem entity or at least introduce parent-child relationship between Directory and FileSystem