Search code examples
javaiofilewriter

Recursive method doesn't work with FileWriter


I have a method that should write down in a file a structure of a given directory in a tree view. But it doesn't write down subfolders and their files, so I tried adding a recursive call, but for some reason it doesn't work. How can i fix it?

public void readFiles() {
        File baseDirectory = new File(path);
        if (baseDirectory.isDirectory()) {
            try (FileWriter writer = new FileWriter("D:/info.txt")) {
                for (File file : baseDirectory.listFiles()) {
                        if (file.isFile()) {
                            writer.append(" |------ " + file.getName());
                            writer.append("\n");
                        } else if (file.isDirectory()) {
                            writer.append(" |+++++ " + file.getName());
                            writer.append("\n");
                            path = file.getPath().replace("\\", "/");
                            readFiles(); // recursive call here

                        }
                }
                writer.flush();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

Main class :

public class Runner {
    public static void main(String[] args) {
        TreeViewer treeViewer = new TreeViewer();
        treeViewer.setPath("D:/test");
        treeViewer.readFiles();
    }
}

[Example of the output file: ][1]


Solution

  • Try this.

    static void tree(File file, String indent, Writer out) throws IOException {
        out.write(indent + file.getName() + System.lineSeparator());
        if (file.isDirectory())
            for (File child : file.listFiles())
                tree(child, indent + "  ", out);
    }
    
    public static void main(String[] args) throws IOException {
        try (Writer out = new FileWriter("D:/info.txt")) {
            tree(new File("D:/test"), "", out);
        }
    }