需求:递归遍历一个目录,筛选出需要查找的文件类型 实现:分别用Java流式实现和递归实现 代码:
package hello;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
/**
* Description:
* <p>
*
* @author shuvidora
* @date 2019/6/12 12:27
*/
class WalkTree {
/**
* 流式实现筛选指定目录下指定类型的文件
*/
public void walkTree() {
Path start = FileSystems.getDefault().getPath("src");
try {
Files.walk(start)
.filter(path -> path.toFile().isFile())
.filter(path -> path.toString().endsWith(".java"))
.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 默认只扫描当前文件夹
* @param f
*/
public void filterFileType(File f) {
filterFileType(f, false);
}
/**
*
* @param file
* @param isRecursive 是否递归子文件夹
*/
public void filterFileType(File file, boolean isRecursive) {
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File f : files) {
if (f.isFile()) {
if (f.getName().endsWith(".java")) {
System.out.println(f.getName());
}
} else if(isRecursive && f.isDirectory()) {
filterFileType(f, true);
}
}
}
}
}
// 枚举实现单例模式,线程安全,非延迟加载
enum FileUtils {
INSTANCE;
private WalkTree instance;
FileUtils() {
instance = new WalkTree();
} // 默认private构造方法
public WalkTree getInstance() {
return instance;
}
}
public class FileTest {
public static void main(String[] args) {
FileUtils main = FileUtils.INSTANCE;
WalkTree walkTree = main.getInstance();
//walkTree.walkTree(); //1
File file = new File("src");
walkTree.filterFileType(file, true); //2
}
}
输出:
//1
src\hello\Counter.java
src\hello\FileTest.java
src\housekeeping\Burrito.java
//2
Counter.java
FileTest.java
Burrito.java