简体   繁体   中英

Google Guava Iterate All Files Starting From a Begin Directory

I use Google Guava at my code. Starting from a directory I want to get all the files by one by (if current file is some special file I will do some process inside it) and at the end I will copy them into another directory(except for some directories.)

I know that there is a copy method at Guava however how can I get all the files under a directory (if there are some directories under starting directory I should get files under it too and if there is any directory under some of that directories I should get them too)

PS 1: If there is any suggestion for copying files you are welcome.

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

PS 3: I use Java 6 at my project.

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

The usage 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 from TreeTraverser 's javadoc , you can choose between three different iteration orders.

如果您可以访问Java 7, walkFileTreeFiles使用walkFileTree

  • Copy file by Guava

    Some Files.copy overloading methods are found in Guava 14.0, for single file copy.

  • Walk files

    As some suggested, you could use recursive call. ( DirectoryScanner you mentioned is good)

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