Kotlin Standard Library JDK 7 extension providing Path utilities and platform-specific implementations for Java NIO and JDK 7+ features
—
Comprehensive file input/output operations including streams, readers/writers, and high-level convenience methods for text and binary data with charset support and proper resource management.
Create input and output streams for low-level file operations.
/**
* Constructs a new InputStream of this file and returns it as a result.
* The options parameter determines how the file is opened.
*/
fun Path.inputStream(vararg options: OpenOption): InputStream
/**
* Constructs a new OutputStream of this file and returns it as a result.
* The options parameter determines how the file is opened.
*/
fun Path.outputStream(vararg options: OpenOption): OutputStreamUsage Examples:
import kotlin.io.path.*
import java.nio.file.Paths
import java.nio.file.StandardOpenOption
val inputFile = Paths.get("/home/user/data.bin")
val outputFile = Paths.get("/home/user/processed.bin")
// Copy binary data using streams
inputFile.inputStream().use { input ->
outputFile.outputStream().use { output ->
input.copyTo(output)
}
}
// Write binary data with specific options
val binaryData = byteArrayOf(0x48, 0x65, 0x6C, 0x6C, 0x6F) // "Hello"
outputFile.outputStream(StandardOpenOption.CREATE, StandardOpenOption.APPEND).use { output ->
output.write(binaryData)
}Create character-based readers and writers with charset support and buffering.
/**
* Returns a new InputStreamReader for reading the content of this file.
* @param charset character set to use for reading text, UTF-8 by default
* @param options options to determine how the file is opened
*/
fun Path.reader(charset: Charset = Charsets.UTF_8, vararg options: OpenOption): InputStreamReader
/**
* Returns a new BufferedReader for reading the content of this file.
* @param charset character set to use for reading text, UTF-8 by default
* @param bufferSize necessary size of the buffer
* @param options options to determine how the file is opened
*/
fun Path.bufferedReader(
charset: Charset = Charsets.UTF_8,
bufferSize: Int = DEFAULT_BUFFER_SIZE,
vararg options: OpenOption
): BufferedReader
/**
* Returns a new OutputStreamWriter for writing the content of this file.
* @param charset character set to use for writing text, UTF-8 by default
* @param options options to determine how the file is opened
*/
fun Path.writer(charset: Charset = Charsets.UTF_8, vararg options: OpenOption): OutputStreamWriter
/**
* Returns a new BufferedWriter for writing the content of this file.
* @param charset character set to use for writing text, UTF-8 by default
* @param bufferSize necessary size of the buffer
* @param options options to determine how the file is opened
*/
fun Path.bufferedWriter(
charset: Charset = Charsets.UTF_8,
bufferSize: Int = DEFAULT_BUFFER_SIZE,
vararg options: OpenOption
): BufferedWriterUsage Examples:
import kotlin.io.path.*
import java.nio.file.Paths
import java.nio.charset.StandardCharsets
val textFile = Paths.get("/home/user/document.txt")
val outputFile = Paths.get("/home/user/processed.txt")
// Read with custom charset
textFile.reader(StandardCharsets.ISO_8859_1).use { reader ->
val content = reader.readText()
println("Content: $content")
}
// Write with buffered writer
outputFile.bufferedWriter(StandardCharsets.UTF_8, bufferSize = 8192).use { writer ->
writer.write("Line 1\n")
writer.write("Line 2\n")
writer.flush()
}
// Process large files efficiently
val largeFile = Paths.get("/home/user/large-text.txt")
largeFile.bufferedReader().use { reader ->
var lineCount = 0
reader.forEachLine { line ->
lineCount++
if (line.contains("ERROR")) {
println("Error found on line $lineCount: $line")
}
}
}High-level operations for reading and writing binary data.
/**
* Gets the entire content of this file as a byte array.
* It's not recommended to use this function on huge files.
*/
fun Path.readBytes(): ByteArray
/**
* Writes an array of bytes to this file.
* By default, the file will be overwritten if it already exists.
*/
fun Path.writeBytes(array: ByteArray, vararg options: OpenOption)
/**
* Appends an array of bytes to the content of this file.
*/
fun Path.appendBytes(array: ByteArray)Usage Examples:
import kotlin.io.path.*
import java.nio.file.Paths
val imageFile = Paths.get("/home/user/image.jpg")
val backupFile = Paths.get("/home/user/backup/image.jpg")
// Read entire file as bytes (use carefully with large files)
val imageData = imageFile.readBytes()
println("Image size: ${imageData.size} bytes")
// Write bytes to new file
backupFile.createParentDirectories()
backupFile.writeBytes(imageData)
// Append binary data
val additionalData = byteArrayOf(0xFF, 0xFE, 0xFD)
backupFile.appendBytes(additionalData)
// Working with smaller binary files
val configData = "key=value\n".toByteArray()
val configFile = Paths.get("/tmp/config.dat")
configFile.writeBytes(configData)High-level operations for reading and writing text with charset support.
/**
* Gets the entire content of this file as a String using UTF-8 or the specified charset.
* It's not recommended to use this function on huge files.
*/
fun Path.readText(charset: Charset = Charsets.UTF_8): String
/**
* Sets the content of this file as text encoded using UTF-8 or the specified charset.
* By default, the file will be overwritten if it already exists.
*/
fun Path.writeText(text: CharSequence, charset: Charset = Charsets.UTF_8, vararg options: OpenOption)
/**
* Appends text to the content of this file using UTF-8 or the specified charset.
*/
fun Path.appendText(text: CharSequence, charset: Charset = Charsets.UTF_8)Usage Examples:
import kotlin.io.path.*
import java.nio.file.Paths
import java.nio.charset.StandardCharsets
val textFile = Paths.get("/home/user/notes.txt")
// Write text content
val notes = """
Meeting Notes - ${java.time.LocalDate.now()}
==========================================
- Discussed project timeline
- Reviewed code architecture
- Planned next sprint
""".trimIndent()
textFile.writeText(notes)
// Read text content
val content = textFile.readText()
println("File content:\n$content")
// Append additional text
textFile.appendText("\n\nAction Items:\n- Update documentation\n- Fix unit tests")
// Work with different charsets
val europeanFile = Paths.get("/home/user/european-text.txt")
val europeanText = "Café, naïve, résumé"
europeanFile.writeText(europeanText, StandardCharsets.ISO_8859_1)
val readEuropeanText = europeanFile.readText(StandardCharsets.ISO_8859_1)
println("European text: $readEuropeanText")Operations for reading and writing files line by line with memory-efficient processing.
/**
* Reads the file content as a list of lines.
* It's not recommended to use this function on huge files.
*/
fun Path.readLines(charset: Charset = Charsets.UTF_8): List<String>
/**
* Writes the specified collection of char sequences to a file terminating each one with the platform's line separator.
* By default, the file will be overwritten if it already exists.
*/
fun Path.writeLines(lines: Iterable<CharSequence>, charset: Charset = Charsets.UTF_8, vararg options: OpenOption): Path
/**
* Writes the specified sequence of char sequences to a file terminating each one with the platform's line separator.
*/
fun Path.writeLines(lines: Sequence<CharSequence>, charset: Charset = Charsets.UTF_8, vararg options: OpenOption): Path
/**
* Appends the specified collection of char sequences to a file terminating each one with the platform's line separator.
*/
fun Path.appendLines(lines: Iterable<CharSequence>, charset: Charset = Charsets.UTF_8): Path
/**
* Appends the specified sequence of char sequences to a file terminating each one with the platform's line separator.
*/
fun Path.appendLines(lines: Sequence<CharSequence>, charset: Charset = Charsets.UTF_8): Path
/**
* Reads this file line by line using the specified charset and calls action for each line.
* You may use this function on huge files.
*/
fun Path.forEachLine(charset: Charset = Charsets.UTF_8, action: (line: String) -> Unit)
/**
* Calls the block callback giving it a sequence of all the lines in this file and closes the reader once
* the processing is complete.
*/
fun <T> Path.useLines(charset: Charset = Charsets.UTF_8, block: (Sequence<String>) -> T): TUsage Examples:
import kotlin.io.path.*
import java.nio.file.Paths
val csvFile = Paths.get("/home/user/data.csv")
val outputFile = Paths.get("/home/user/processed.csv")
// Write lines from collection
val headers = listOf("Name", "Age", "City")
val data = listOf(
"Alice,25,New York",
"Bob,30,San Francisco",
"Charlie,28,Chicago"
)
csvFile.writeLines(headers + data)
// Read all lines at once (use carefully with large files)
val allLines = csvFile.readLines()
println("Total lines: ${allLines.size}")
// Process lines efficiently for large files
csvFile.forEachLine { line ->
if (line.startsWith("Error:")) {
println("Found error: $line")
}
}
// Use lines with sequence for memory-efficient processing
val errorCount = csvFile.useLines { lines ->
lines.count { it.contains("ERROR") }
}
println("Total errors: $errorCount")
// Transform and write lines
val transformedLines = csvFile.useLines { lines ->
lines.drop(1) // Skip header
.map { line ->
val parts = line.split(",")
if (parts.size >= 3) {
"${parts[0].uppercase()},${parts[1]},${parts[2].uppercase()}"
} else {
line
}
}
.toList()
}
outputFile.writeLines(listOf("NAME,AGE,CITY") + transformedLines)
// Append processed results
val summary = listOf(
"",
"Summary:",
"Total records: ${transformedLines.size}",
"Processed on: ${java.time.LocalDateTime.now()}"
)
outputFile.appendLines(summary)Combining different I/O operations for complex file processing scenarios.
Usage Examples:
import kotlin.io.path.*
import java.nio.file.Paths
import java.nio.file.StandardOpenOption
val logFile = Paths.get("/var/log/application.log")
val archiveFile = Paths.get("/var/log/archive/application-${java.time.LocalDate.now()}.log")
// Rotate log file
if (logFile.exists() && logFile.fileSize() > 10_000_000) { // 10MB
// Copy current log to archive
archiveFile.createParentDirectories()
logFile.copyTo(archiveFile, overwrite = true)
// Clear current log
logFile.writeText("")
}
// Process configuration file with validation
val configFile = Paths.get("/etc/myapp/config.properties")
val backupConfigFile = Paths.get("/etc/myapp/config.properties.backup")
if (configFile.exists()) {
// Create backup
configFile.copyTo(backupConfigFile, overwrite = true)
// Read and validate configuration
val config = mutableMapOf<String, String>()
configFile.forEachLine { line ->
val trimmed = line.trim()
if (trimmed.isNotEmpty() && !trimmed.startsWith("#")) {
val parts = trimmed.split("=", limit = 2)
if (parts.size == 2) {
config[parts[0].trim()] = parts[1].trim()
}
}
}
// Write validated configuration
val validatedLines = config.map { (key, value) -> "$key=$value" }
configFile.writeLines(validatedLines)
}
// Batch process multiple files
val dataDir = Paths.get("/home/user/data")
val processedDir = Paths.get("/home/user/processed")
processedDir.createDirectories()
dataDir.listDirectoryEntries("*.txt").forEach { inputFile ->
val outputFile = processedDir / inputFile.name
inputFile.useLines { lines ->
val processedLines = lines
.filter { it.isNotBlank() }
.map { it.trim().uppercase() }
.toList()
outputFile.writeLines(processedLines)
}
println("Processed: ${inputFile.name}")
}Install with Tessl CLI
npx tessl i tessl/maven-org-jetbrains-kotlin--kotlin-stdlib-jdk7