简体   繁体   中英

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]

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM