Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scan a folder in Java?

How can I get list all the files within a folder recursively in Java?

like image 311
Lipis Avatar asked Oct 09 '08 20:10

Lipis


People also ask

What does the files list () method in Java do?

list() returns the array of files and directories in the directory defined by this abstract path name. The method returns null, if the abstract pathname does not denote a directory.

Can Java scanner read file?

Scanner is a utility class in java. util package which can parse primitive types and strings using regular expressions. It can read text from any object which implements the Readable interface. We can also construct a Scanner that produces values scanned from the specified file.


1 Answers

Not sure how you want to represent the tree? Anyway here's an example which scans the entire subtree using recursion. Files and directories are treated alike. Note that File.listFiles() returns null for non-directories.

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 offers a couple of improvements. For example, DirectoryStream provides one result at a time - the caller no longer has to wait for all I/O operations to complete before acting. This allows incremental GUI updates, early cancellation, etc.

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

Note that the dreaded null return value has been replaced by IOException.

Java 7 also offers a 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;         }     }); } 
like image 180
volley Avatar answered Sep 21 '22 18:09

volley