Say I have something like this:
new File("test").eachFile() { file-> println file.getName() }
This prints the full filename of every file in the test
directory. Is there a Groovy way to get the filename without any extension? (Or am I back in regex land?)
GetFileNameWithoutExtension(ReadOnlySpan<Char>) Returns the file name without the extension of a file path that is represented by a read-only character span.
Windows file names have two parts separated by a period: first, the file name, and second, a three- or four-character extension that defines the file type. In expenses. xlsx, for example, the first part of the file name is expenses and the extension is xlsx.
I believe the grooviest way would be:
file.name.lastIndexOf('.').with {it != -1 ? file.name[0..<it] : file.name}
or with a simple regexp:
file.name.replaceFirst(~/\.[^\.]+$/, '')
also there's an apache commons-io java lib for that kinda purposes, which you could easily depend on if you use maven:
org.apache.commons.io.FilenameUtils.getBaseName(file.name)
The cleanest way.
String fileWithoutExt = file.name.take(file.name.lastIndexOf('.'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With