Jak skanować folder w Javie?

Jak mogę wyświetlić rekurencyjnie listę wszystkich plików w folderze w Javie?

Author: Lipis, 2008-10-10

7 answers

Nie wiesz, jak chcesz reprezentować drzewo? W każdym razie oto przykład, który skanuje cały poddrzew za pomocą rekurencji. Pliki i katalogi są traktowane podobnie. Zauważ, że Plik.listFiles () zwraca null dla niekatalogów.

public static void main(String[] args) {
    Collection<File> all = new ArrayList<File>();
    addTree(new File("."), all);
    System.out.println(all);
}

static void addTree(File file, Collection<File> all) {
    File[] children = file.listFiles();
    if (children != null) {
        for (File child : children) {
            all.add(child);
            addTree(child, all);
        }
    }
}

Java 7 oferuje kilka ulepszeń. Na przykład, DirectoryStream dostarcza jeden wynik na raz - wywołujący nie musi już czekać na zakończenie wszystkich operacji We/Wy przed uruchomieniem. Pozwala to na przyrostowe aktualizacje GUI, wczesne anulowanie itp.

static void addTree(Path directory, Collection<Path> all)
        throws IOException {
    try (DirectoryStream<Path> ds = Files.newDirectoryStream(directory)) {
        for (Path child : ds) {
            all.add(child);
            if (Files.isDirectory(child)) {
                addTree(child, all);
            }
        }
    }
}

Zauważ, że straszna wartość zwracana null została zastąpiona przez IOException.

Java 7 oferuje również Tree walker :

static void addTree(Path directory, final Collection<Path> all)
        throws IOException {
    Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                throws IOException {
            all.add(file);
            return FileVisitResult.CONTINUE;
        }
    });
}
 69
Author: volley,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-05-15 19:30:50
import java.io.File;
public class Test {
    public static void main( String [] args ) {
        File actual = new File(".");
        for( File f : actual.listFiles()){
            System.out.println( f.getName() );
        }
    }
}

Wyświetla niewyraźnie pliki i foldery.

Zobacz metody w klasie plików, aby je uporządkować lub uniknąć drukowania katalogów itp.

Http://java.sun.com/javase/6/docs/api/java/io/File.html

 21
Author: OscarRyz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-10-09 20:46:57

Sprawdź Apache Commons FileUtils (listFiles, iterateFiles, etc.). Ładne metody wygody do robienia tego, co chcesz, a także stosowania filtrów.

Http://commons.apache.org/io/api-1.4/org/apache/commons/io/FileUtils.html

 18
Author: Brandon DuRette,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-10-09 21:39:38

Możesz również użyć FileFilter interfejs do filtrowania tego, co chcesz. Najlepiej jest użyć, gdy tworzysz anonimową klasę, która ją implementuje:

import java.io.File;
import java.io.FileFilter;

public class ListFiles {
    public File[] findDirectories(File root) { 
        return root.listFiles(new FileFilter() {
            public boolean accept(File f) {
                return f.isDirectory();
            }});
    }

    public File[] findFiles(File root) {
        return root.listFiles(new FileFilter() {
            public boolean accept(File f) {
                return f.isFile();
            }});
    }
}
 6
Author: Leonel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-10-10 15:54:32
public static void directory(File dir) {
    File[] files = dir.listFiles();
    for (File file : files) {
        System.out.println(file.getAbsolutePath());
        if (file.listFiles() != null)
            directory(file);        
    }
} 

Tutaj dir jest katalog do zeskanowania. np. c:\

 2
Author: Rohit sharma,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-26 15:27:51

Wizualizacja struktury drzewa była dla mnie najwygodniejszym sposobem:

public static void main(String[] args) throws IOException {
    printTree(0, new File("START/FROM/DIR"));
}

static void printTree(int depth, File file) throws IOException { 
    StringBuilder indent = new StringBuilder();
    String name = file.getName();

    for (int i = 0; i < depth; i++) {
        indent.append(".");
    }

    //Pretty print for directories
    if (file.isDirectory()) { 
        System.out.println(indent.toString() + "|");
        if(isPrintName(name)){
            System.out.println(indent.toString() + "*" + file.getName() + "*");
        }
    }
    //Print file name
    else if(isPrintName(name)) {
        System.out.println(indent.toString() + file.getName()); 
    }
    //Recurse children
    if (file.isDirectory()) { 
        File[] files = file.listFiles(); 
        for (int i = 0; i < files.length; i++){
            printTree(depth + 4, files[i]);
        } 
    }
}

//Exclude some file names
static boolean isPrintName(String name){
    if (name.charAt(0) == '.') {
        return false;
    }
    if (name.contains("svn")) {
        return false;
    }
    //.
    //. Some more exclusions
    //.
    return true;
}
 1
Author: Ohad Dan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-05-08 10:06:43

W JDK7 "więcej funkcji NIO" powinno mieć metody do stosowania wzorca odwiedzającego na drzewie plików lub tylko na bezpośredniej zawartości katalogu - nie ma potrzeby znajdowania wszystkich plików w potencjalnie ogromnym katalogu przed iteracją nad nimi.

 0
Author: Tom Hawtin - tackline,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-10-10 08:13:16