标签:over 失败 directory import visit move bool dea led
package a
import java.io.IOException
import java.nio.file.*
import java.nio.file.attribute.BasicFileAttributes
fun main(args: Array<String>) {
val path = Paths.get("F:\\杨旭升\\dev\\dev_java")
remove_recursively(path, 0, { name ->
name == "out" || name == "target" || name == "node_modules" || name == ".idea" || name == ".cache"
}, { name ->
name.endsWith(".iml")
});
}
/*
@author 张天笑
@time 2019/1/24 10:35
@path 起始目录
@depth 遍历深度, 从根目录开始算 最多遍历几层文件夹
@dir_condition 遍历到目录时执行的判断条件
file_condition 遍历到文件时执行的判断条件
*/
fun remove_recursively(
path: Path, depth: Int
, dir_condition: (name: String) -> Boolean
, file_condition: (name: String) -> Boolean
) {
// 遍历限制深度100
if (depth == 100) {
return
}
try {
Files.walkFileTree(path, object : SimpleFileVisitor<Path>() {
// 访问成功的回调, 可能因为权限问题, 无法访问
@Throws(IOException::class)
override fun preVisitDirectory(dir: Path, attrs: BasicFileAttributes): FileVisitResult {
// 第一个子目录对象是..
if (dir == path) {
return FileVisitResult.CONTINUE
}
val file = dir.toFile()
val name = file.name
// 删除符合条件的文件夹
if (dir_condition(name)) {
try {
println("删除目录: $file.absolutePath")
file.deleteRecursively()
} catch (e: Exception) {
println("删除失败: ${file.absolutePath}")
}
}
// 递归遍历子文件夹
else {
remove_recursively(dir, depth + 1, dir_condition, file_condition)
}
return FileVisitResult.CONTINUE
}
@Throws(IOException::class)
override fun visitFile(path: Path, attrs: BasicFileAttributes): FileVisitResult {
val file = path.toFile()
val name = file.name
if (file_condition(name)) {
// 删除符合条件的文件
try {
println("删除文件: ${file.absolutePath}")
file.delete()
} catch (e: Exception) {
println("删除失败: ${file.absolutePath}")
}
}
return FileVisitResult.CONTINUE
}
@Throws(IOException::class)
override fun visitFileFailed(file: Path, exc: IOException?): FileVisitResult {
System.out.println(exc)
return FileVisitResult.CONTINUE
}
@Throws(IOException::class)
override fun postVisitDirectory(dir: Path, exc: IOException?): FileVisitResult {
return super.postVisitDirectory(dir, exc)
}
})
} catch (e: IOException) {
e.printStackTrace()
}
}
/*
$RECYCLE
* */
标签:over 失败 directory import visit move bool dea led
原文地址:https://www.cnblogs.com/zhangtianxiao/p/10362779.html