Google Guava Iterate all files starting from the start directory

I use Google Guava in my code. Starting from the directory, I want to get all the files one at a time (if the current file is a special file, I will do some process inside it), and in the end I will copy them to another directory (with the exception of some directories.)

I know that there is a copy method in Guava, but how can I get all the files under a directory (if there are several directories in the initial directory, I should get the files under it too, and if there is any directory under some of these directories, I must get them too)

PS 1: If you have any suggestions about copying files, please.

PS 2: I think this conversation is related to my question: http://code.google.com/p/guava-libraries/issues/detail?id=578

PS 3: I use Java 6 in my project.

+5
source share
3 answers

With Guava 15 you can use Files.fileTreeTraverser().

Using is very simple:

File rootDir = ...; //this is your root directory
for (File f : Files.fileTreeTraverser().preOrderTraversal(rootDir)) {
    // do whatever you need with the file/directory

    // if you need the relative path, with respect to rootDir
    Path relativePath = rootDir.toPath().getParent().relativize(f.toPath());
}

As you can read TreeTraverserjavadoc , you can choose one of three different iteration orders.

+13
source

If you have access to Java 7, use walkFileTreeat Files.

+2
source
  • Guava

    Files.copy Guava 14.0 .

  • , . (DirectoryScanner )

0

All Articles