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

Solution 1:

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)

Solution 2:

The cleanest way.

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

Solution 3:

Simplest way is:

'file.name.with.dots.tgz' - ~/\.\w+$/​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

Result is:

file.name.with.dots

Solution 4:

new File("test").eachFile() { file->  
    println file.getName().split("\\.")[0]
}

This works well for file names like: foo, foo.bar

But if you have a file foo.bar.jar, then the above code prints out: foo If you want it to print out foo.bar instead, then the following code achieves that.

new File("test").eachFile() { file->  
    def names = (file.name.split("\\.")
    def name = names.size() > 1 ? (names - names[-1]).join('.') : names[0]
    println name
}

Solution 5:

The FilenameUtils class, which is part of the apache commons io package, has a robust solution. Example usage:

import org.apache.commons.io.FilenameUtils

String filename = '/tmp/hello-world.txt'
def fileWithoutExt = FilenameUtils.removeExtension(filename)

This isn't the groovy way, but might be helpful if you need to support lots of edge cases.