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

name.remal.java.io.File.kt Maven / Gradle / Ivy

package name.remal

import java.io.File
import java.lang.System.currentTimeMillis

private val baseTempDirectory = File(System.getProperty("java.io.tmpdir")).absoluteFile.createDirectories()

@JvmOverloads
fun newTempFile(prefix: String = "temp-", suffix: String = ".temp", doDeleteOnExit: Boolean = false): File {
    val now = currentTimeMillis()
    var counter = 0
    while (true) {
        val file = File(baseTempDirectory, encodeURIComponent("$prefix$now-$counter$suffix"))
        if (file.createNewFile()) {
            return file.also {
                if (doDeleteOnExit) it.deleteOnExit()
            }
        }
        ++counter
    }
}

@JvmOverloads
fun newTempDir(prefix: String = "temp-", doDeleteOnExit: Boolean = false): File {
    val now = currentTimeMillis()
    var counter = 0
    while (true) {
        val dir = File(baseTempDirectory, encodeURIComponent("$prefix$now-$counter"))
        if (dir.mkdir()) {
            return dir.also {
                if (doDeleteOnExit) it.deleteOnExitRecursively()
            }
        }
        ++counter
    }
}


fun File.forceDelete() = apply { toPath().delete() }
fun File.forceDeleteRecursively() = apply { toPath().deleteRecursively() }

fun File.createDirectories() = apply { toPath().createDirectories() }
fun File.createParentDirectories() = apply { toPath().createParentDirectories() }

fun File.deleteOnExitRecursively() = apply { FilesToDeleteContainer.files.add(this.absoluteFile) }

private object FilesToDeleteContainer {

    val files = concurrentSetOf()

    init {
        Runtime.getRuntime().addShutdownHook(Thread {
            files.forEach {
                try {
                    it.forceDeleteRecursively()
                } catch (ignored: Throwable) {
                    // do nothing
                }
            }
        })
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy