Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Guava Iterate All Files Starting From a Begin Directory

Tags:

java

file

guava

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.

like image 596
kamaci Avatar asked Feb 14 '13 19:02

kamaci


1 Answers

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.

like image 144
Paolo Fulgoni Avatar answered Sep 21 '22 01:09

Paolo Fulgoni