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 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 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; } }