I recently had to recursively search for files under a directory. I think that Java standard api has such a function, but it is not surprising.
__2016-12-29 Addendum ___: Although it is written that "it is not in the standard", it has been pointed out that there are actually various things. See the comments section for details.
For example, suppose you have a directory with the following structure:
D:\>tree D:\temp /f
List of folder paths:Volume Data
Volume serial number is C4C7-10BC
D:\TEMP
│ Text 0.txt
│
├─ Folder 1
│ │ Text 1.txt
│ │
│ └─ Folder 1-1
│ Text 1-1.txt
│
├─ Folder 2
│ Text 1.txt
│
└─ Folder 3
Text 3.txt
To recursively search for files under this D: \ temp
:
package folder;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class FolderUtils {
public static void main(String[] args) {
String absolutePath = "D:\\temp";
List<File> files = FolderUtils.findAllFile(absolutePath);
for (File file : files) System.out.println(file.getAbsolutePath());
// D:\temp\Folder 2\Text 1.txt
// D:\temp\Folder 1\Folder 1-1\Text 1-1.txt
// D:\temp\Folder 1\Text 1.txt
// D:\temp\Folder 3\Text 3.txt
// D:\temp\Text 0.txt
}
/**
*Recursively search for files under a given directory.
* @param absolutePath The absolute path of the directory.
* @List of return files
*/
public static List<File> findAllFile(String absolutePath) {
List<File> files = new ArrayList<>();
Stack<File> stack = new Stack<>();
stack.add(new File(absolutePath));
while (!stack.isEmpty()) {
File item = stack.pop();
if (item.isFile()) files.add(item);
if (item.isDirectory()) {
for (File child : item.listFiles()) stack.push(child);
}
}
return files;
}
}
The algorithm is depth-first search. If it's a directory, it's as simple as searching under it, otherwise it's listed. I chose to implement using a stack instead of a recursive call that is compatible with depth-first search-not because I aimed for an efficient implementation-but because I just wanted to know that Java has a stack (I wanted to use it). ´ ・ ω ・ ) I'm sorry I don't have a big reason (´ ・ ω ・
)
Recommended Posts