File I/O, Serialization, JSON, Testing, and Tooling
Work with files and external data formats, and learn the testing habits and tooling practices expected in real Kotlin projects.
Inside this chapter
- Reading and Writing Files
- Serialization and JSON
- Why Testing Matters
- Basic Unit Test Example
- Tooling in Team Environments
- Practical Example
Series navigation
Study the chapters in order for the clearest path from Kotlin setup and syntax to coroutines, backend work, clean design, multiplatform thinking, and advanced engineering practice. Use the navigation at the bottom to move smoothly through the full tutorial series.
Reading and Writing Files
import java.io.File
val content = File("notes.txt").readText()
File("output.txt").writeText("Processed: $content")
File operations are common in CLI tools, local utilities, export jobs, ETL flows, and test fixtures.
Serialization and JSON
Applications constantly exchange structured data. Kotlin projects often use serialization libraries to convert objects to and from JSON.
@kotlinx.serialization.Serializable
data class Customer(val id: Int, val name: String)
Once data contracts cross service boundaries, serialization rules become part of system correctness.
Why Testing Matters
Testing is not just about preventing bugs. It is also about documenting behavior, enabling safe refactoring, and supporting team confidence during change.
Basic Unit Test Example
import kotlin.test.Test
import kotlin.test.assertEquals
class PriceCalculatorTest {
@Test
fun calculatesDiscountedPrice() {
assertEquals(90, 100 - 10)
}
} Tooling in Team Environments
- Static analysis and linting
- Formatting conventions
- Gradle build automation
- CI test execution
- Coverage and mutation-awareness discussions
Practical Example
A finance reconciliation tool may read CSV or JSON files, transform records, validate fields, and write output reports. Without testing and serialization discipline, such tools can quietly produce incorrect business results.