Search

Dark theme | Light theme

September 17, 2025

Groovy Goodness: Getting Extension And BaseName For File And Path

Groovy 5 adds the extension methods getExtension and getBaseName to the File and Path classes. You can invoke them as properties for a File and Path objects. Also the asBoolean method is added. This mean you can use a File or Path instance in a boolean context. If the underlying file exists true is returned and false otherwise.

The following example shows how to use the new extension methods for the File class:

def file = new File("sample.txt")

assert file.extension == 'txt'
assert file.baseName == 'sample'
assert !file  // File doesn't exist.

// Create file by writing content.
file.write("Some content")
assert file // File does exist now.

The same extension methods are added to the Path class and the following example shows their usage:

import java.nio.file.Path

def path = Path.of("sample.text")

assert path.extension == 'text'
assert path.baseName == 'sample'
assert !path  // Path does not exist.

// Create path by setting content.
path.text = "Some content"
assert path  // Now path exists.

Written with Groovy 5.0.0.