ํด๋์ ํ์ ํ์ผ๊น์ง ์ง์ฐ๊ธฐ
fun delete(directoryPath : String) {
val dir = File(directoryPath)
dir.deleteRecursively()
}
File.deleteRecursively()์ ๋ด๋ถ ์ฝ๋๋ฅผ ์ดํด๋ณด์๋ค.
/**
* Delete this file with all its children.
* Note that if this operation fails then partial deletion may have taken place.
*
* @return `true` if the file or directory is successfully deleted, `false` otherwise.
*/
public fun File.deleteRecursively(): Boolean = walkBottomUp().fold(true, { res, it -> (it.delete() || !it.exists()) && res })
fold ํจ์๋ ์ด๋ฌํ๋ค
public inline fun <T, R> kotlin.sequences.Sequence<T>.fold(initial: R, operation: (R, T) -> R): R { /* compiled code */ }
File.deleteRecursively()๋ ํด๋ ๋ฐ ํ์ผ์ ์กด์ฌ ์ฌ๋ถ๋ฅผ ๋ด๋ถ์์ ์ฒดํฌํด์ฃผ๊ณ ์๋ค.๐
1) walkBottomUp()์ด Bottom Up ์์๋ก ํ์ผ Sequence๋ฅผ ๋ฐํํด์ค๋ค.
/**
* Gets a sequence for visiting this directory and all its content in bottom-up order.
* Depth-first search is used and directories are visited after all their files.
*/
public fun File.walkBottomUp(): FileTreeWalk = walk(FileWalkDirection.BOTTOM_UP)
public fun File.walk(direction: FileWalkDirection = FileWalkDirection.TOP_DOWN): FileTreeWalk =
FileTreeWalk(this, direction)
/**
* This class is intended to implement different file traversal methods.
* It allows to iterate through all files inside a given directory.
*
* Use [File.walk], [File.walkTopDown] or [File.walkBottomUp] extension functions to instantiate a `FileTreeWalk` instance.
* If the file path given is just a file, walker iterates only it.
* If the file path given does not exist, walker iterates nothing, i.e. it's equivalent to an empty sequence.
*/
public class FileTreeWalk private constructor(
private val start: File,
private val direction: FileWalkDirection = FileWalkDirection.TOP_DOWN,
private val onEnter: ((File) -> Boolean)?,
private val onLeave: ((File) -> Unit)?,
private val onFail: ((f: File, e: IOException) -> Unit)?,
private val maxDepth: Int = Int.MAX_VALUE
) : Sequence<File> {
...
}
2) fold ์คํ
public fun File.deleteRecursively(): Boolean =
walkBottomUp().fold(true, { res, it -> (it.delete() || !it.exists()) && res })
res๋ Boolean ๊ฐ, it์ bottom up ์์๋ก ๋ฐํ๋๋ File์ด๋ค.
fold ์์ operation์ walkBottomUp()์ผ๋ก ๋ฐ์ File์ ๋ฐํ์ด ๋๋ ๋๊น์ง ์คํ๋๋ค.
์ฒซ res ๊ฐ์ true. ํด๋ ๋ฐ ํ์ผ์ด ์กด์ฌํ๋ฉด(!it.exists() -> false) ํ์ผ์ delete๋ฅผ ์์ผ์ค๋ค. delete๊ฐ ์ฑ๊ณต์ ์ผ๋ก ์ด๋ฃจ์ด์ง๋ฉด true๋ฅผ ๋ฐํํ๊ณ ๋ค์ operation ์คํ์ด ์ด๋ฃจ์ด์ง๋ค.
ํ์ผ์ด ์กด์ฌํ์ง ์์ผ๋ฉด ๋ค์ operation์ผ๋ก ๋์ด๊ฐ๋ค. : !it.exists() -> true
delete์ ๋ฐํ๊ฐ์ด false๋ก ๋์ฌ ๊ฒฝ์ฐ(ํ์ผ delete๊ฐ ์ ์์ ์ผ๋ก ์ด๋ฃจ์ด์ง์ง ์์ ๊ฒฝ์ฐ) ๋ค์ operation์ res ๊ฐ์ false๋ก ๋์จ๋ค.(it.delete() || !it.exists() -> false) ์ด๋ ๊ฒ ๋๋ฉด ํ์์ operation์ return ๊ฐ๋ค์ ๊ณ์ false๋ก ๋์ฌ ๊ฒ์ด๊ณ , ํ์ผ์ ์กด์ฌ ์ฌ๋ถ๋ฅผ ์ฐพ๊ฑฐ๋ ์ญ์ ๋ ์ด๋ฃจ์ด ์ง์ง ์์ ๊ฒ์ด๋ค.(res -> false) ํ ๋ฒ res ๊ฐ์ด false๊ฐ ๋๋ฉด ๋ค์ ํด๋ ๋ฐ ํ์ผ๋ค์ ์์ (delete)์ ์ด๋ฃจ์ด์ง์ง ์๋ ๊ฒ์ด๋ค.