30 lines
1.1 KiB
Kotlin
30 lines
1.1 KiB
Kotlin
package filesystem
|
|
|
|
import java.nio.file.FileAlreadyExistsException
|
|
import java.nio.file.FileSystemException
|
|
import java.nio.file.Files
|
|
import java.nio.file.Path
|
|
|
|
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 -> Files.createFile(path)
|
|
is FSFolder -> Files.createDirectory(path)
|
|
}
|
|
} catch (_: FileAlreadyExistsException) {} // Allow files/folders to already exist.
|
|
when (entry) {
|
|
is FSFile -> Files.write(path, entry.content.toByteArray())
|
|
is FSFolder -> queue.addAll(entry.entries.map { it to path })
|
|
}
|
|
}
|
|
}
|
|
} |