Display all directories and files contained in them

1

I'm trying to mount a file tree where in addition to displaying the directories of the computer is also displayed its files. The code I've done below is only listing the specified directory, in this case C:\ . But the directories contained within C: such as "Program Files" does not display what's inside.

package arvore;

import java.io.File;

public class Arvore {

public static void main(String[] args) {

    File folder = new File("C:\");

    File[] listOfFiles = folder.listFiles();

    for (int i = 0; i < listOfFiles.length; i++) {
        if (listOfFiles[i].isFile()) {
            System.out.println("Este é Arquivo " + listOfFiles[i].getName());
        } else if (listOfFiles[i].isDirectory()) {
            System.out.println("***ESTE E DIRETÓRIO " + listOfFiles[i].getName());
            }
        }

    }
}

The question is how it would look to display all including subdirectories.

    
asked by anonymous 07.05.2015 / 21:24

2 answers

0

Use recursion:

public static void main(String[] args) {

    File folder = new File("C:\");

    for (File arquivo : folder.listFiles()) {
        listarArquivos(arquivo);
    }

}

public static void listarArquivos(File raiz) {
    if (raiz.isFile()) {
        System.out.println("Este é Arquivo " + raiz.getName());
        return;
    }
    System.out.println("***ESTE E DIRETÓRIO " + raiz.getName());
    for (File no : raiz.listFiles()) {
        listarArquivos(no);
    }

}
    
07.05.2015 / 21:32
0

This one lists everything! Sub-directories, and all files.

import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;


public class Teste {

    public static void main(String[] args) {
        try {
            Path startPath = Paths.get("c:/");
            Files.walkFileTree(startPath, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult preVisitDirectory(Path dir,
                        BasicFileAttributes attrs) {
                    System.out.println("Diretório: " + dir.toString());
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
                    System.out.println("Arquivo: " + file.toString());    
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFileFailed(Path file, IOException e) {
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}   
    
07.05.2015 / 21:35