All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.dankito.utils.extensions.PathExtensions.kt Maven / Gradle / Ivy

The newest version!
package net.dankito.utils.extensions

import net.dankito.utils.extensions.PathExtensions.Companion.log
import net.dankito.utils.io.FileUtils
import org.slf4j.LoggerFactory
import java.nio.ByteBuffer
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.attribute.BasicFileAttributes
import java.nio.file.attribute.FileAttribute
import java.nio.file.attribute.FileTime


class PathExtensions {
    companion object {
        internal val log = LoggerFactory.getLogger(PathExtensions::class.java)
    }
}


val Path.exists: Boolean
    get() = Files.exists(this)

val Path.absolutePath: String
    get() = this.toAbsolutePath().toString()

val Path.size: Long
    get() {
        try {
            return Files.size(this)
        } catch (e: Exception) { log.error("Could not get file size of Path '$this'", e) }

        return -1
    }

val Path.isDirectory: Boolean
    get() = Files.isDirectory(this)

val Path.isRegularFile: Boolean
    get() = Files.isRegularFile(this)

val Path.creationTimeMillis: Long
    get() = getMillisFor { it.creationTime() }

val Path.lastAccessTimeMillis: Long
    get() = getMillisFor { it.lastAccessTime() }

val Path.lastModifiedTimeMillis: Long
    get() = getMillisFor { it.lastModifiedTime() }

val Path.basicFileAttributes: BasicFileAttributes?
    get() {
        try {
            return Files.readAttributes(this, BasicFileAttributes::class.java)
        } catch (e: Exception) { log.error("Could not get BasicFileAttributes of Path '$this'", e) }

        return null
    }

fun Path.getMillisFor(chooseTimeCallback: (BasicFileAttributes) -> FileTime): Long {
    basicFileAttributes?.let { attributes ->
        return chooseTimeCallback(attributes).toMillis()
    }

    return -1
}


fun Path.createFileIfNotExists(vararg attributes: FileAttribute<*>) {
    if (this.exists == false) { // call to Files.createFile() for an existing file would result in a FileAlreadyExistsException
        if (this.parent?.exists == false) { // if the parent directory/-ies do not exist Files.createFile() would result in an IOException
            this.parent?.createDirectoryIfNotExists()
        }

        Files.createFile(this, *attributes)
    }
}

fun Path.createDirectoryIfNotExists(vararg attributes: FileAttribute<*>) {
    Files.createDirectories(this, *attributes)
}


@JvmOverloads
fun Path.forEachBlock(blockSize: Int = FileUtils.DefaultFileOperationBufferSize, action: (buffer: ByteBuffer, bytesRead: Int) -> Unit) {
    FileUtils().forEachBlock(this, blockSize, action)
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy