38 lines
1.2 KiB
Kotlin
38 lines
1.2 KiB
Kotlin
package filesystem
|
|
|
|
import java.nio.file.FileAlreadyExistsException
|
|
import java.nio.file.FileSystemException
|
|
import java.nio.file.Path
|
|
import kotlin.io.path.createDirectory
|
|
import kotlin.io.path.createFile
|
|
import kotlin.io.path.writeText
|
|
|
|
class FSCreator {
|
|
/**
|
|
* Create entry, leaving existing folders' contents, but overwriting existing files.
|
|
*/
|
|
@Throws(FileSystemException::class)
|
|
fun create(
|
|
entryToCreate: FSEntry,
|
|
destination: String,
|
|
) {
|
|
val queue = ArrayDeque<Pair<FSEntry, Path>>()
|
|
queue.add(entryToCreate to Path.of(destination))
|
|
|
|
while (queue.isNotEmpty()) {
|
|
val (entry, dest) = queue.removeFirst()
|
|
val path = dest.resolve(entry.name)
|
|
try {
|
|
when (entry) {
|
|
is FSFile -> path.createFile()
|
|
is FSFolder -> path.createDirectory()
|
|
}
|
|
} catch (_: FileAlreadyExistsException) {
|
|
} // Allow files/folders to already exist.
|
|
when (entry) {
|
|
is FSFile -> path.writeText(entry.content)
|
|
is FSFolder -> queue.addAll(entry.entries.map { it to path })
|
|
}
|
|
}
|
|
}
|
|
} |