简体   繁体   English

Google Guava迭代从Begin目录开始的所有文件

[英]Google Guava Iterate All Files Starting From a Begin Directory

I use Google Guava at my code. 我在我的代码中使用Google Guava。 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) 我知道在Guava有一个复制方法,但是如何在目录下获取所有文件(如果在起始目录下有一些目录,我应该在它下面获取文件,如果在某些目录下有任何目录,我应该得到他们)

PS 1: If there is any suggestion for copying files you are welcome. PS 1:如果有任何复制文件的建议,欢迎您。

PS 2: I think this conversation is related with my question: http://code.google.com/p/guava-libraries/issues/detail?id=578 PS 2:我认为此对话与我的问题有关: http//code.google.com/p/guava-libraries/issues/detail?id = 578

PS 3: I use Java 6 at my project. PS 3:我在我的项目中使用Java 6。

Since Guava 15 you can use Files.fileTreeTraverser() . 从Guava 15开始,您可以使用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. 正如您可以从TreeTraverser的javadoc中读取的TreeTraverser ,您可以在三种不同的迭代顺序中进行选择。

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

  • Copy file by Guava 由Guava复制文件

    Some Files.copy overloading methods are found in Guava 14.0, for single file copy. 一些Files.copy重载方法可以在Guava 14.0中找到,用于单个文件复制。

  • Walk files 走路文件

    As some suggested, you could use recursive call. 正如一些人建议的那样,你可以使用递归调用。 ( DirectoryScanner you mentioned is good) (你提到的DirectoryScanner很好)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM