Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a filename without extension in Kotlin

Tags:

io

kotlin

What is the best way to get the filename from a String or a File object, removing the extension?

like image 285
Nino van Hooff Avatar asked Dec 18 '17 15:12

Nino van Hooff


People also ask

How to get the filename without the extension in Java?

getNameWithoutExtension() method. It allows us to remove the extension from the given filename easily. The implementation is pretty straightforward. If the filename contains dots, the method cuts from the last dot to the end of the filename.


1 Answers

I found that creating a File object is a straightforward way to achieve this. No actual file will be created on disk. But take care that only the last extension will be removed:

File("myFile.txt").nameWithoutExtension
File("myFile.tar.gz").nameWithoutExtension

result:

"myFile"

"myFile.tar"

like image 154
Nino van Hooff Avatar answered Sep 24 '22 06:09

Nino van Hooff