Files
timi-io/src/main/java/com/imyeyu/io/TreeFile.java
T
Timi 33177f5ded
CI/CD / build-deploy (pull_request) Successful in 40s
v0.0.3
2026-03-21 18:14:57 +08:00

73 lines
1.4 KiB
Java

package com.imyeyu.io;
import com.imyeyu.java.TimiJava;
import lombok.Getter;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
/**
* @author 夜雨
* @version 2024-06-30 16:26
*/
@Getter
public class TreeFile extends File {
private List<TreeFile> children;
public TreeFile(String pathname) {
super(pathname);
if (isDirectory()) {
build();
}
}
private void build() {
if (children != null) {
return;
}
File[] files = listFiles();
if (files == null) {
return;
}
children = new ArrayList<>();
for (int i = 0; i < files.length; i++) {
TreeFile treeFile = new TreeFile(files[i].getAbsolutePath());
children.add(treeFile);
if (treeFile.isDirectory()) {
treeFile.build();
}
}
}
public void foreach(ForeachCallback callback) throws Exception {
Stack<TreeFile> stack = new Stack<>();
stack.push(this);
while (!stack.isEmpty()) {
TreeFile item = stack.pop();
String relPath = item.getAbsolutePath().substring(Math.min(item.getAbsolutePath().length(), getAbsolutePath().length() + 1));
callback.handler(relPath, item);
if (TimiJava.isNotEmpty(item.children)) {
for (int i = 0, l = item.children.size(); i < l; i++) {
stack.push(item.children.get(i));
}
}
}
}
/**
*
*
* @author 夜雨
* @since 2024-12-09 23:00
*/
public interface ForeachCallback {
void handler(String relPath, File file) throws Exception;
}
}