DEV Community

loizenai
loizenai

Posted on

Kotlin get File Name example

https://grokonez.com/kotlin/kotlin-get-file-name-example

Kotlin get File Name example

This Kotlin tutorial shows you ways to get File Name from full path with Kotlin Regex and extension functions.

I. Technology

  • Java 1.8
  • Kotlin 1.1.2

    II. Practice

    1. Using Regex

    
    package com.javasampleapproach.filename

fun main(args: Array) {

val fullPath = "JavaSampleApproach/Kotlin/Practice/getFileNameExample.kt"

val regex = """(.+)/(.+)\.(.+)""".toRegex()
val matchResult = regex.matchEntire(fullPath)

if (matchResult != null) {
    val (directory, fileName, extension) = matchResult.destructured
    println("dir: $directory | fileName: $fileName | extension: $extension")
}
Enter fullscreen mode Exit fullscreen mode

}

Result:


dir: JavaSampleApproach/Kotlin/Practice | fileName: getFileNameExample | extension: kt

2. Using Kotlin String extension function

More at:
https://grokonez.com/kotlin/kotlin-get-file-name-example

Kotlin get File Name example

Top comments (0)