Kotlin – Get All Files in a Specific Directory

Get All Files in a Specific Directory in Kotlin

To retrieve all files from a specific directory in Kotlin, you can use listFile() method of the File class from the java.io package.

In this tutorial, we will go through a step by step process of obtaining a list of all files in a specified directory in Kotlin.

Steps to Get All Files in a Directory in Kotlin

To get all files from a directory in Kotlin, follow these steps:

  1. Import the File class from the java.io package.
  2. Create a File object pointing to the directory you want to explore.
  3. Use the listFiles() method to obtain an array of File objects representing the files in the directory.
  4. Optionally, filter the results to exclude directories if only files are needed.

Kotlin Example Program to Get All Files in a Directory

The following is an example program that lists all files in a directory named 'exampleDir'.

Kotlin Example Program to Get All Files in a Directory

Main.kt

import java.io.File

fun main() {
    val directoryPath = "exampleDir" // Replace with your directory path
    val directory = File(directoryPath)

    val files = directory.listFiles()?.filter { it.isFile }
    files?.forEach { file ->
        println(file.name)
    } ?: println("No files found or directory does not exist.")
}

Output

data.json
example.txt
output.txt

The output will display the names of all files in the specified directory. If the directory does not exist or contains no files, it will indicate so.

Summary

In this Kotlin tutorial, we learned how to list all files in a specific directory using File.listFiles() method, with an example.