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
Newsletter
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?
  • Testing Java and Spring Applications With Kotlin: Low-Risk to Adoption
  • Developer’s Checklist: How to Build an FHE Application
  • The Self-Healing Directory: Architecting AI-Driven Security for Active Directory

Trending

  • DZone's Article Submission Guidelines
  • How to Submit a Post to DZone
  • Designing Memory Architecture for Stateful AI Agents: Short-Term Context and Long-Term Persistence
  • Part 4: Multi-Agent Orchestration — Pairing Goose With Quarkus Flow State Machines

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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
·
Jun. 07, 16 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
13.6K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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?
  • Testing Java and Spring Applications With Kotlin: Low-Risk to Adoption
  • Developer’s Checklist: How to Build an FHE Application
  • The Self-Healing Directory: Architecting AI-Driven Security for Active Directory

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • 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