Kotlin

Kotlin: Read, Write, Modify, Delete & List Files

Photo of Yatin BatraYatin BatraApril 14th, 2025Last Updated: April 14th, 2025
0 288 3 minutes read

Kotlin is fully interoperable with Java and widely used for Android development, server-side applications, and more. Let us delve into understanding how to read, write, modify, delete, and list files in Kotlin.

1. Introduction to Kotlin

Kotlin is a modern, statically typed programming language developed byJetBrains and officially supported byGoogle for Android development. It is designed to be concise, expressive, and interoperable with Java, making it a powerful choice for various software development projects. Kotlin is widely used inmobile app development,web applications,server-side programming, and evendata science.

1.1 Use Cases of Kotlin

  • Android Development: Kotlin is the preferred language for Android app development, offering null safety, extension functions, and coroutines for asynchronous programming.
  • Backend Development: With frameworks like Ktor and Spring Boot, Kotlin is widely used for server-side applications.
  • Web Development: Kotlin/JS allows developers to write frontend applications using Kotlin, compiling to JavaScript.
  • Cross-Platform Development: Kotlin Multiplatform enables code sharing between Android, iOS, and other platforms.
  • Data Science & Machine Learning: Kotlin is emerging in data science, integrating with tools like Apache Spark.
  • Game Development: Some game developers use Kotlin with game engines such as LibGDX.

1.2 Benefits of Kotlin

  • Concise Syntax: Reduces boilerplate code compared to Java.
  • Interoperability with Java: Kotlin can seamlessly work with existing Java codebases.
  • Null Safety: Eliminates null pointer exceptions through safe call operators.
  • Coroutines for Asynchronous Programming: Provides lightweight threads for better performance.
  • Smart Type Inference: Reduces the need for explicit type declarations.
  • Modern Functional Features: Supports lambda expressions, higher-order functions, and more.

1.3 Kotlin vs. Java: A Comparison

FeatureKotlinJava
ConcisenessRequires less code, reducing redundancyMore verbose with boilerplate code
Null SafetyBuilt-in null safety featuresProne to NullPointerExceptions
CoroutinesUses coroutines for efficient multithreadingRelies on traditional threads and Executors
Interoperability100% interoperable with JavaNot interoperable with Kotlin
Extension FunctionsAllows adding functions to existing classesRequires utility classes for similar functionality
Default Parameter ValuesSupports default values in functionsNeeds method overloading

2. Code Example

The following Kotlin program demonstrates reading, writing, modifying, deleting, and listing files in a directory.

import java.io.Fileimport java.io.IOExceptionfun main() {    val fileName = "example.txt"    val directoryName = "test_directory"    // Create a File object    val file = File(fileName)    try {        // Writing to a file        file.writeText("Hello, Kotlin!") // Writing initial text to the file        println("File written successfully.")        // Reading a file        val content = file.readText() // Reading the content of the file        println("File Content:\n$content")        // Modifying a file (appending text)        file.appendText("\nThis is additional content.") // Appending new content to the file        println("File modified successfully.")        // Reading the modified file        println("Updated File Content:\n${file.readText()}")    } catch (e: IOException) {        println("Error while handling file: ${e.message}")    }    try {        // Creating a directory        val directory = File(directoryName)        if (!directory.exists()) {            if (directory.mkdir()) {                println("Directory '$directoryName' created.")            } else {                println("Failed to create directory '$directoryName'.")            }        }        // Listing files in a directory        println("Files in current directory:")        File(".").listFiles()?.forEach { println(it.name) }    } catch (e: IOException) {        println("Error while handling directory: ${e.message}")    }    try {        // Deleting a file        if (file.exists() && file.delete()) {            println("File '$fileName' deleted successfully.") // Deleting the file        } else {            println("Failed to delete the file or file does not exist.")        }    } catch (e: IOException) {        println("Error while deleting file: ${e.message}")    }}

2.1 Code Explanation

This Kotlin program demonstrates essential file operations with proper exception handling. It begins by creating a file object and writing “Hello, Kotlin!” into it, followed by reading and printing its content. The file is then modified by appending additional text and re-read to display the updated content. Exception handling is implemented using try-catch blocks to gracefully manage potential `IOException` errors during file operations. The program then checks for a directory named “test_directory” and creates it if it does not exist, listing all files in the current directory afterward. Finally, it attempts to delete the file only if it exists, ensuring safe execution. These enhancements make the program more robust by handling errors effectively and preventing unexpected crashes.

2.2 Code Output

When executed, the code generates the following output in the IDE console.

File written successfully.File Content:Hello, Kotlin!File modified successfully.Updated File Content:Hello, Kotlin!This is additional content.Directory 'test_directory' created.Files in current directory:example.txttest_directoryFile 'example.txt' deleted successfully.

3. Conclusion

Kotlin makes file handling operations simple and efficient with its standard library functions. The example above demonstrates how to perform essential file operations such as reading, writing, modifying, deleting, and listing files in a directory.

Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of Yatin BatraYatin BatraApril 14th, 2025Last Updated: April 14th, 2025
0 288 3 minutes read
Photo of Yatin Batra

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.