Search

Dark theme | Light theme
Showing posts with label GroovyGoodness:Files. Show all posts
Showing posts with label GroovyGoodness:Files. Show all posts

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.

May 17, 2016

Groovy Goodness: Creating Files And Directories With Nice DSL Using FileTreeBuilder

Groovy has a lot of nice and useful gems. One of them is the FileTreeBuilder class. With this class we can create directories and files using a nice DSL with a builder syntax. The code already reflects the hierarchy of the directory structure, which makes it so more readable. We can use an explicit way of referring to methods in the FileTreeBuilder class, but there is also support for a more dynamic version, where Groovy's dynamic nature comes to play.

In the first example we use the explicit method names. We can use the method dir to create directories and the method file to create a file. We can specify a name for the file and also contents:

// Create new FileTreeBuilder. Default the current
// directory is the base directory for creating new
// files and directories.
// We can pas another directory in the constructor as
// the base directory.
final FileTreeBuilder treeBuilder = new FileTreeBuilder(new File('tree'))

// Add a file and set the contents using
// a closure. The delegate of the closure
// is the File object.
treeBuilder.file('README.adoc') {
    write '''\
        = Groovy rocks!

        Hidden features in Groovy are also cool.

        '''.stripIndent()
}

// Append to file contents with a String argument.
treeBuilder.file('README.adoc', '== Extra heading')

final File sample = new File('sample')
sample.text = '''\
= Another sample

Testing the Groovy FileTreeBuilder.
'''

// Or we use another File's contents to append to a file.
treeBuilder.file('README1.adoc', sample)

// Create a new directory.
treeBuilder.dir('out')

// Create subdirectories and files
// using a closure. The delegate is
// is FileTreeBuilder again.
treeBuilder.dir('src') {
    dir('docs') {
        file('manuscript.adoc') {
            // Another way to write file contents.
            withWriter('UTF-8') { writer ->
                writer.write '= Building Apps With Grails 3'
            }
        }
    }
}

assert new File('tree/README.adoc').exists()
assert new File('tree/src/docs/manuscript.adoc').exists()
assert new File('tree/src/docs/manuscript.adoc').text == '= Building Apps With Grails 3'

We can achieve the same result using a more compact DSL. The FileTreeBuilder will determine if a directory or file needs to be created. Notice that contents is always append to a file:

// We can even use a shorter syntax with the
// FileTreeBuilder where the node names are the name
// of a directory to be created (argument is a closure),
// or the name of a file and some contents.
// Notice that with the DSL all file contents is
// appended to existing file contents.
// We need to delete an existing file first if we
// don't want to append the contents.

final File newDir = new File('dsl')

// Remove existing dir, so file contents is
// only set by the FileTreeBuilder DSL,
// otherwise content is added to the existing files.
if (newDir.exists()) {
    newDir.deleteDir()
}

newDir.mkdirs()
final FileTreeBuilder dir = new FileTreeBuilder(newDir)

dir {
    // Node name is the file name, followed by the contents.
    'README.adoc'('''\
        = Groovy rocks!

        Hidden features in Groovy are also cool.

        '''.stripIndent())

    'README.adoc'('== Extra heading')

     // We cannot use a closure argument with this DSL,
     // like with the builder. The DSL assume that a node with a
     // closure is a directory.
     // But we can use the File object argument to set
     // the file contents.
    'README1.adoc'(sample)
}

// If name is follwed by closure than a directory
// name is assumed and created.
dir.out {}

// Created directory with subdirectories.
dir.src {
    // The name of the node is the directory name.
    docs {
        // And create file in the src/docs directory.
        'manuscript.adoc'('= Building Apps With Grails 3')
    }
}

assert new File('dsl/README.adoc').exists()
assert new File('dsl/src/docs/manuscript.adoc').exists()
assert new File('dsl/src/docs/manuscript.adoc').text == '= Building Apps With Grails 3'

Written with Groovy 2.4.6.

January 26, 2013

Groovy Goodness: Calculating Directory Size

Groovy 2.1 adds the method directorySize() to File objects. If the File object is a directory then the total size of all files is calculated. Notice this method will go recursively through all subdirectories so it might take some time before the method returns. If we invoke the method on a File object that is not a directory an IllegalArgumentException is thrown.

def sampleDir = new File('sample')
def sampleDirSize = sampleDir.directorySize()

println sampleDirSize // Outputs size in bytes, eg. 130615981

Using Groovy from the command-line we can easily get the directory size like this:

$ groovy -e "println new File('.').directorySize()"

Written with Groovy 2.1

August 9, 2010

Groovy Goodness: Simple File Renaming

Groovy has a lot of simple useful methods to make every day life easier. In Groovy 1.7.4 we can use the renameTo() method on a File object. We pass a String argument with the new name of the file.

def file = new File('test.groovy')
file.text = 'simple content'
file.renameTo 'newname.groovy'

def newFile = new File('newname.groovy')
assert newFile.exists()
assert 'simple content' == newFile.text

April 28, 2010

Groovy Goodness: Traversing a Directory

Groovy adds the traverse() method to the File class in version 1.7.2. We can use this method to traverse a directory tree and invoke a closure to process the files and directories. If we look at the documentation we see we can also pass a map with a lot of possible options to influence the processing.

import static groovy.io.FileType.*
import static groovy.io.FileVisitResult.*

def groovySrcDir = new File(System.env['GROOVY_HOME'], 'src/')

def countFilesAndDirs = 0
groovySrcDir.traverse {
    countFilesAndDirs++
}
println "Total files and directories in ${groovySrcDir.name}: $countFilesAndDirs"

def totalFileSize = 0
def groovyFileCount = 0
def sumFileSize = { 
    totalFileSize += it.size()
    groovyFileCount++
}
def filterGroovyFiles = ~/.*\.groovy$/
groovySrcDir.traverse type: FILES, visit: sumFileSize, nameFilter: filterGroovyFiles
println "Total file size for $groovyFileCount Groovy source files is: $totalFileSize"

def countSmallFiles = 0
def postDirVisitor = {
    if (countSmallFiles > 0) {
     println "Found $countSmallFiles files with small filenames in ${it.name}"
 }
    countSmallFiles = 0
}
groovySrcDir.traverse(type: FILES, postDir: postDirVisitor, nameFilter: ~/.*\.groovy$/) {
    if (it.name.size() < 15) {
     countSmallFiles++
    }
}

April 27, 2010

Groovy Goodness: Working on Files or Directories (or Both) with FileType

Working with files in Groovy is very easy. We have a lot of useful methods available in the File class. For example we can run a Closure for each file that can be found in a directory with the eachFile() method. Since Groovy 1.7.1 we can define if we only want to process the directories, files or both. To do this we must pass a FileType constant to the method. See the following example code:

import groovy.io.FileType

// First create sample dirs and files.
(1..3).each { 
 new File("dir$it").mkdir() 
}
(1..3).each { 
 def file = new File("file$it")
 file << "Sample content for ${file.absolutePath}"
}

def currentDir = new File('.')
def dirs = []
currentDir.eachFile FileType.DIRECTORIES, {
    dirs << it.name
}
assert 'dir1,dir2,dir3' == dirs.join(',')

def files = []
currentDir.eachFile(FileType.FILES) {
    files << it.name
}
assert 'file1,file2,file3' == files.join(',')

def found = []
currentDir.eachFileMatch(FileType.ANY, ~/.*2/) {
   found << it.name
}

assert 'dir2,file2' == found.join(',')

August 27, 2009

Groovy Goodness: Working with Files

When we write code in Java to work with files we must write a lot of boilerplate code to make sure all streams are opened and closed correctly and provide exception handling. The Commons IO package already helps, but Groovy makes working with files so easy. Groovy adds a lot of useful methods to the java.io.File class. We can use simple properties to write and read text, methods to traverse the file system and methods to filter contents.

Here is a Groovy script with different samples of working with files:

// Normal way of creating file objects.
def file1 = new File('groovy1.txt')
def file2 = new File('groovy2.txt')
def file3 = new File('groovy3.txt')

// Writing to the files with the write method:
file1.write 'Working with files the Groovy way is easy.\n'

// Using the leftShift operator:
file1 << 'See how easy it is to add text to a file.\n'

// Using the text property:
file2.text = '''We can even use the text property of
a file to set a complete block of text at once.'''

// Or a writer object:
file3.withWriter('UTF-8') { writer ->
    writer.write('We can also use writers to add contents.')
}

// Reading contents of files to an array:
def lines = file1.readLines()
assert 2 == lines.size()
assert 'Working with files the Groovy way is easy.' == lines[0]

// Or we read with the text property:
assert 'We can also use writers to add contents.' == file3.text

// Or with a reader:
count = 0
file2.withReader { reader -> 
    while (line = reader.readLine()) {
        switch (count) {
            case 0: 
                assert 'We can even use the text property of' == line
                break
            case 1:
                assert 'a file to set a complete block of text at once.' == line
                break
        }
        count++
    }
}

// We can also read contents with a filter:
sw = new StringWriter()
file1.filterLine(sw) { it =~ /Groovy/ }
assert 'Working with files the Groovy way is easy.\r\n' == sw.toString()

// We can look for files in the directory with different methods.
// See for a complete list the File GDK documentation.
files = []
new File('.').eachFileMatch(~/^groovy.*\.txt$/) { files << it.name }
assert ['groovy1.txt', 'groovy2.txt', 'groovy3.txt'] == files

// Delete all files:
files.each { new File(it).delete() }