Directories in Kotlin

Our first program will demonstrate working with directories in Kotlin. Here’s the full source code:

import java.io.File
import java.nio.file.*

fun check(e: Exception?) {
    if (e != null) {
        throw e
    }
}

fun main() {
    // Create a new sub-directory in the current working directory.
    val subdir = File("subdir")
    subdir.mkdir()

    // When creating temporary directories, it's good practice to delete them afterwards.
    // We'll use 'use' to automatically close and delete the directory.
    Files.createTempDirectory("temp").use { tempDir ->
        println("Created temp directory: ${tempDir.toAbsolutePath()}")
        
        // Helper function to create a new empty file.
        fun createEmptyFile(name: String) {
            File(name).writeText("")
        }

        createEmptyFile("subdir/file1")

        // We can create a hierarchy of directories, including parents.
        File("subdir/parent/child").mkdirs()

        createEmptyFile("subdir/parent/file2")
        createEmptyFile("subdir/parent/file3")
        createEmptyFile("subdir/parent/child/file4")

        // list directory contents
        println("Listing subdir/parent")
        File("subdir/parent").listFiles()?.forEach { 
            println("  ${it.name} ${it.isDirectory}")
        }

        // Change the current working directory
        val originalDir = System.getProperty("user.dir")
        System.setProperty("user.dir", "subdir/parent/child")

        // Now we'll see the contents of subdir/parent/child when listing the current directory.
        println("Listing subdir/parent/child")
        File(".").listFiles()?.forEach { 
            println("  ${it.name} ${it.isDirectory}")
        }

        // Change back to where we started.
        System.setProperty("user.dir", originalDir)

        // We can also visit a directory recursively, including all its sub-directories.
        println("Visiting subdir")
        File("subdir").walkTopDown().forEach { 
            println("  ${it.path} ${it.isDirectory}")
        }
    }
}

To run the program, save it as Directories.kt and use kotlinc to compile and kotlin to run:

$ kotlinc Directories.kt -include-runtime -d Directories.jar
$ kotlin Directories.jar
Listing subdir/parent
  child true
  file2 false
  file3 false
Listing subdir/parent/child
  file4 false
Visiting subdir
  subdir true
  subdir/file1 false
  subdir/parent true
  subdir/parent/child true
  subdir/parent/child/file4 false
  subdir/parent/file2 false
  subdir/parent/file3 false

This Kotlin program demonstrates various operations with directories:

  1. Creating directories
  2. Creating temporary directories
  3. Creating empty files
  4. Listing directory contents
  5. Changing the current working directory
  6. Walking a directory tree recursively

Note that Kotlin provides a more idiomatic and safer way to work with files and directories compared to some other languages. For example, we use use for automatic resource management, and Kotlin’s null-safety features help prevent null pointer exceptions when working with files and directories.