Kotlin – Read, Write, Modify, Delete, and List Files

In this article, we will cover how to read, write, modify, delete, and list files in Kotlin and compare them with Java equivalents.

Table of contents

1. Reading a File in Kotlin

Reading a file is a fundamental operation. We can use Kotlin’s readText(), readLines() to read a file efficiently.

FileReadExample.kt

import java.io.File

fun main() {
    val file = File("sample.txt")
    
    // Read entire content as a single string
    val content = file.readText()
    println("File Content:\n$content")
    
    // Read line by line
    val lines = file.readLines()
    lines.forEach { println(it) }
}

Java Equivalent

FileReadExample.java

import java.io.*;
import java.nio.file.*;
import java.util.List;

public class FileReadExample {
    public static void main(String[] args) throws IOException {
        Path path = Paths.get("sample.txt");
        
        // Read entire file as a string
        String content = Files.readString(path);
        System.out.println("File Content:\n" + content);
        
        // Read file line by line
        List<String> lines = Files.readAllLines(path);
        lines.forEach(System.out::println);
    }
}

Kotlin provides a more concise and readable approach compared to Java.

2. Writing to a File in Kotlin

We can use writeText(), appendText(), or printWriter() to write to a file.

FileWriteExample.kt

import java.io.File

fun main() {
    val file = File("output.txt")
    
    // Write text to a file
    file.writeText("Hello, Kotlin!")
    
    // Append text to the file
    file.appendText("\nAppending more text.")
}

Java Equivalent

FileWriteExample.java

import java.io.*;
import java.nio.file.*;

public class FileWriteExample {
    public static void main(String[] args) throws IOException {
        Path path = Paths.get("output.txt");
        
        // Write to a file
        Files.writeString(path, "Hello, Java!");
        
        // Append text
        Files.writeString(path, "\nAppending more text.", StandardOpenOption.APPEND);
    }
}

Kotlin’s approach is more straightforward and avoids dealing with FileWriter or BufferedWriter explicitly.

3. Modifying a File in Kotlin

To modify a file, we typically read its contents, modify the text, and then write it back.

FileModifyExample.kt

import java.io.File

fun main() {
    val file = File("data.txt")
    
    // Read content
    val content = file.readText()
    
    // Modify content
    val modifiedContent = content.replace("old text", "new text")
    
    // Write back to file
    file.writeText(modifiedContent)
}

Java Equivalent

FileModifyExample.java

import java.io.*;
import java.nio.file.*;

public class FileModifyExample {
    public static void main(String[] args) throws IOException {
        Path path = Paths.get("data.txt");
        
        // Read content
        String content = Files.readString(path);
        
        // Modify content
        String modifiedContent = content.replace("old text", "new text");
        
        // Write back to file
        Files.writeString(path, modifiedContent);
    }
}

4. Deleting a File in Kotlin

We can use the delete() function to remove a file.

FileDeleteExample.kt

import java.io.File

fun main() {
    val file = File("toDelete.txt")
    
    if (file.exists()) {
        file.delete()
        println("File deleted successfully.")
    } else {
        println("File does not exist.")
    }
}

Java Equivalent

FileDeleteExample.java

import java.io.File;

public class FileDeleteExample {
    public static void main(String[] args) {
        File file = new File("toDelete.txt");
        
        if (file.exists()) {
            file.delete();
            System.out.println("File deleted successfully.");
        } else {
            System.out.println("File does not exist.");
        }
    }
}

5. Listing Files in a Directory

We can list all files in a directory using listFiles() in Kotlin.

ListFilesExample.kt

import java.io.File

fun main() {
    val directory = File("./")
    
    val files = directory.listFiles()
    files?.forEach { println(it.name) }
}

Java Equivalent

ListFilesExample.java

import java.io.File;

public class ListFilesExample {
    public static void main(String[] args) {
        File directory = new File("./");

        File[] files = directory.listFiles();
        if (files != null) {
            for (File file : files) {
                System.out.println(file.getName());
            }
        }
    }
}

6. Conclusion

Kotlin simplifies file handling compared to Java by providing clean and concise functions. Whether we need to read, write, modify, delete, or list files, Kotlin’s approach makes it efficient and easy to understand.

7. References:

mkyong

Founder of Mkyong.com, passionate Java and open-source technologies. If you enjoy my tutorials, consider making a donation to these charities.

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments