DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Why "Polyglot Programming" or "Do It Yourself Programming Languages" or "Language Oriented Programming" sucks?
  • The Self-Healing Directory: Architecting AI-Driven Security for Active Directory
  • Scaling Identity Governance Without Connectors: The LDAP Directory IGA Integration Pattern
  • Why Developers Should Pay Attention to Internal Directory Security

Trending

  • Testing Strategies for Web Development Code Generated by LLMs
  • Context Rot: Why Your AI Agent Gets Worse the Longer It Works
  • Parallel Kafka Batch Processing With Kotlin Coroutines in Spring Boot
  • Encryption Won't Survive Quantum Computing: What to Do?
  1. DZone
  2. Coding
  3. Languages
  4. Groovy Goodness: Creating Files and Directories With a Nice DSL Using FileTreeBuilder

Groovy Goodness: Creating Files and Directories With a Nice DSL Using FileTreeBuilder

One of the reasons Groovy has attained such popularity is it's ability to create and use DSLs in programming. This article goes into the inbuilt FileTreeBuilder class as a great example of this.

By 
Hubert Klein Ikkink user avatar
Hubert Klein Ikkink
·
Jun. 07, 16 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
13.5K Views

Join the DZone community and get the full member experience.

Join For Free

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.

Domain-Specific Language Directory Groovy (programming language)

Published at DZone with permission of Hubert Klein Ikkink. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Why "Polyglot Programming" or "Do It Yourself Programming Languages" or "Language Oriented Programming" sucks?
  • The Self-Healing Directory: Architecting AI-Driven Security for Active Directory
  • Scaling Identity Governance Without Connectors: The LDAP Directory IGA Integration Pattern
  • Why Developers Should Pay Attention to Internal Directory Security

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook