Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Kotlin
Stage 5: Specialization

Part 08 / Topic 1 of 7

File: checking and creating paths

java.io.File represents a path on disk -- it does not mean the file exists; it's just a handle you can ask questions of, or use to create something.

import java.io.File

val notes = File("notes.txt")
println("notes.txt exists before writing: ${notes.exists()}")

notes.writeText("First line of notes.\n")
println("notes.txt exists after writing: ${notes.exists()}")
println("Is a file: ${notes.isFile}")
println("Is a directory: ${notes.isDirectory}")
println("Absolute path: ${notes.absolutePath}")
println("Size in bytes: ${notes.length()}")
notes.txt exists before writing: false
notes.txt exists after writing: true
Is a file: true
Is a directory: false
Absolute path: /private/tmp/kt-part8-run1/notes.txt
Size in bytes: 21

(The absolute path varies by machine and working directory -- everything else on this page is exact, reproducible output.)

mkdirs() creates a directory, and any missing parent directories along the way, in one call -- it returns true only if it actually created something:

val reportsDir = File("reports")
println("reports/ exists before mkdirs(): ${reportsDir.exists()}")
val created = reportsDir.mkdirs()
println("mkdirs() created it: $created")
println("reports/ exists now: ${reportsDir.exists()}, isDirectory: ${reportsDir.isDirectory}")

val insideReports = File(reportsDir, "daily.txt")
insideReports.writeText("Daily report placeholder")
println("reports/daily.txt exists: ${insideReports.exists()}")
reports/ exists before mkdirs(): false
mkdirs() created it: true
reports/ exists now: true, isDirectory: true
reports/daily.txt exists: true

File(reportsDir, "daily.txt") builds a path by joining a parent File and a child name -- cleaner than gluing strings with "reports/daily.txt" by hand, and it uses the right path separator for whatever OS the program runs on.

Full program: examples/01_file_basics.kt.

Done here? The practice set for Part 8 — including the solutions — is on the part page.

Search the guide