Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does groovy have an easy way to get a filename without the extension?

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?)

like image 664
Electrons_Ahoy Avatar asked Oct 14 '09 23:10

Electrons_Ahoy


People also ask

How can I find the file name without extension?

GetFileNameWithoutExtension(ReadOnlySpan<Char>) Returns the file name without the extension of a file path that is represented by a read-only character span.

Can you give an extension for a filename How is it separated with the filename?

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.


2 Answers

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) 
like image 171
Nikita Volkov Avatar answered Sep 25 '22 18:09

Nikita Volkov


The cleanest way.

String fileWithoutExt = file.name.take(file.name.lastIndexOf('.'))

like image 44
Pier Avatar answered Sep 21 '22 18:09

Pier