[utils][K/N] Added some util functions to File

This commit is contained in:
Igor Chevdar
2022-08-04 12:33:53 +03:00
committed by Space
parent 85800b4f9f
commit b82554dea1
@@ -36,7 +36,7 @@ data class File constructor(internal val javaPath: Path) {
get() = File(canonicalPath)
val name: String
get() = javaPath.fileName.toString().removeSuffixIfPresent("/") // https://bugs.java.com/bugdatabase/view_bug.do?bug_id=8153248
get() = javaPath.fileName.toString().removeSuffixIfPresent(separator) // https://bugs.java.com/bugdatabase/view_bug.do?bug_id=8153248
val extension: String
get() = name.substringAfterLast('.', "")
val parent: String
@@ -70,6 +70,8 @@ data class File constructor(internal val javaPath: Path) {
sourcePath.recursiveCopyTo(destPath, resetTimeAttributes = resetTimeAttributes)
}
fun renameTo(destination: File) = javaPath.toFile().renameTo(destination.javaPath.toFile())
fun mkdirs() = Files.createDirectories(javaPath)
fun delete() = Files.deleteIfExists(javaPath)
fun deleteRecursively() = postorder{Files.delete(it)}
@@ -119,11 +121,13 @@ data class File constructor(internal val javaPath: Path) {
}
fun deleteOnExit(): File {
// Works only on the default file system,
// Works only on the default file system,
// but that's okay for now.
javaPath.toFile().deleteOnExit()
return this // Allow streaming.
}
fun createNew() = javaPath.toFile().createNewFile()
fun readBytes() = Files.readAllBytes(javaPath)
fun writeBytes(bytes: ByteArray) = Files.write(javaPath, bytes)
fun appendBytes(bytes: ByteArray)
@@ -135,6 +139,12 @@ data class File constructor(internal val javaPath: Path) {
fun writeText(text: String): Unit = writeLines(listOf(text))
fun appendLines(lines: Iterable<String>) {
Files.write(javaPath, lines, StandardOpenOption.APPEND)
}
fun appendText(text: String): Unit = appendLines(listOf(text))
fun forEachLine(action: (String) -> Unit) {
Files.lines(javaPath).use { lines ->
lines.forEach { action(it) }
@@ -167,6 +177,7 @@ data class File constructor(internal val javaPath: Path) {
get() = File(System.getProperty("java.home"))
val pathSeparator = java.io.File.pathSeparator
val separator = java.io.File.separator
val separatorChar = java.io.File.separatorChar
}
fun readStrings() = mutableListOf<String>().also { list -> forEachLine{list.add(it)}}