File
- Kotlin course
- Intermediate
- Lesson 94/116
- 5 min
Learn file operations with java.io.File.
File: File path
In Kotlin, file operations use the java.io.File class. A File object represents a path on disk; it does not load the content. The path is passed to the constructor as a string.
import java.io.File
val f = File("kayit.txt")A valid path does not mean the file exists. To check existence call f.exists(); it returns true when the file is present. To read content use readText, to write use writeText; these will be covered in detail in later lessons.
File methods
The File class offers several methods to manage the file. exists() checks presence, readText() reads all content as a single string, writeText(text) writes the given string to the file and readLines() returns lines as a list.
val f = File("kayit.txt")
f.writeText("Hello")
println(f.exists()) // true
println(f.readText()) // HelloThese methods open the file, perform the operation and close it. You do not need to close anything yourself. For large files, prefer line-by-line reading over readText; that is a topic for later.
Practice Write to a file and read it back
Create a path with val f = File("kayit.txt"). Write to it with f.writeText("Hello world"). Read it back and print with println(f.readText()). Do not forget the import java.io.File import.
Starter code
import java.io.File
// Create a File object for the path kayit.txt
// write "Hello world" to it, then read and println
fun main() {
// write here
}Sample solution
fun main() {
val f = File("kayit.txt")
f.writeText("Hello world")
println(f.readText())
}Expected output
Hello world
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does File("kayit.txt") represent?
- A file path Correct answer
- The file content
- A folder listing
- A byte array
Explanation: A File represents a path; it does not load content.
2 Create a File object
val f = ____("kayit.txt")
val f = File("kayit.txt")
Explanation: File("kayit.txt") creates a path representation.
3 Match the File methods
| Term | Meaning |
|---|---|
File("a.txt") |
Path representation |
.exists() |
Is it there? |
.readText() |
Reads text |
.writeText() |
Writes text |