io.slink.files.file-utils.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of slink-zero Show documentation
Show all versions of slink-zero Show documentation
Zero dependenices library to boost your Kotlin development
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
}