树形打印日志
fun main() {
val root = Environment.getExternalStorageDirectory()
tree(root)
}
private fun tree(dir: File) {
Log.d("Bob", dir.path)
dfsLog(dir)
}
private fun dfsLog(dir: File, indent: String = "") {
val files = dir.listFiles() ?: return
val size = files.size
files.forEachIndexed { index, file ->
val last = index == size - 1
Log.d("Bob", "${indent + if (last) "└─ " else "├─ "}${file.name}")
dfsLog(file, indent + if (last) " " else "│ ")
}
}
合并为一个方法
private fun tree(dir: File, indent: String = "", level: Int = 0) {
if (level == 0) Log.d("Bob", dir.path)
val files = dir.listFiles() ?: return
val size = files.size
files.forEachIndexed { index, file ->
val last = index == size - 1
Log.d("Bob", "${indent + if (last) "└─ " else "├─ "}${file.name}")
tree(file, indent + if (last) " " else "│ ", level + 1)
}
}
自定义输出日志
private fun tree(
dir: File,
onLog: (File) -> String = File::getName
) {
Log.d("Bob", dir.path)
dfsLog(dir, onLog = onLog)
}
private fun dfsLog(dir: File, indent: String = "", onLog: (File) -> String) {
val files = dir.listFiles() ?: return
val size = files.size
files.forEachIndexed { index, file ->
val last = index == size - 1
Log.d("Bob", "${indent + if (last) "└─ " else "├─ "}${onLog(file)}")
dfsLog(file, indent + if (last) " " else "│ ", onLog)
}
}
非递归 dfs
// 先序遍历非递归(preOrder)
private fun tree(root: File) {
Log.d("Bob", root.path)
// 三元组:文件、日志缩进的前缀、是否是所在文件夹的最后一个文件
val stack = Stack<Triple<File, String, Boolean>>()
root.listFiles()?.reversed()?.forEachIndexed { index, file ->
stack.push(Triple(file, "", index == 0))
}
while (stack.isNotEmpty()) {
val (dir, indent, last) = stack.pop()
Log.d("Bob", "${indent + if (last) "└─ " else "├─ "}${dir.name}")
dir.listFiles()?.reversed()?.forEachIndexed { index, file ->
stack.push(Triple(file, indent + if (last) " " else "│ ", index == 0))
}
}
}