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

io.slink.files.file-utils.kt Maven / Gradle / Ivy

The newest version!
package io.slink.files

import org.slf4j.LoggerFactory
import java.io.BufferedWriter
import java.io.File
import java.io.InputStream

private val log = LoggerFactory.getLogger("io.slink.files")

fun workingDirectory(): File {
    return File(System.getProperty("user.dir"))
}

fun File.splitLines(outputDirectory: File, linesPerFile: Int): List {
    return inputStream().use {
        it.splitLines(outputDirectory, linesPerFile, this.nameWithoutExtension, this.extension)
    }
}

fun InputStream.splitLines(outputDirectory: File,
                           linesPerFile: Int,
                           baseName: String,
                           extension: String = ""): List {
    val files = mutableListOf()
    var crtFileWriter: BufferedWriter? = null
    var fileIndex = 0

    bufferedReader()
            .useLines { lines ->
                lines.forEachIndexed { index, line ->
                    if (crtFileWriter == null) {
                        val nextFile = File(outputDirectory, baseName + "-${fileIndex + 1}." + extension)
                        log.info("Creating split file $nextFile")
                        files.add(nextFile)
                        crtFileWriter = nextFile.bufferedWriter()
                    }
                    crtFileWriter!!.write(line)
                    crtFileWriter!!.write("\n")
                    if (index % linesPerFile == linesPerFile - 1) {
                        crtFileWriter!!.close()
                        crtFileWriter = null
                        fileIndex++
                    }
                }
            }
    crtFileWriter?.close()

    return files
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy