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")
	}
}

Result:


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

2. Using Kotlin String extension function


package com.javasampleapproach.filename

fun main(args: Array) {

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

	val directory = fullPath.substringBeforeLast("/")
	val fullName = fullPath.substringAfterLast("/")
	val fileName = fullName.substringBeforeLast(".")
	val extension = fullName.substringAfterLast(".")

	println("dir: $directory | fileName: $fileName | extension: $extension")
}

Result:


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

Leave a Reply

Your email address will not be published. Required fields are marked *