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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Why "Polyglot Programming" or "Do It Yourself Programming Languages" or "Language Oriented Programming" sucks?
  • Apache Doris vs Elasticsearch: An In-Depth Comparative Analysis
  • Doris vs Elasticsearch: A Comparison and Practical Cost Case Study
  • Managing AWS Managed Microsoft Active Directory Objects With AWS Lambda Functions

Trending

  • Building Reliable LLM-Powered Microservices With Kubernetes on AWS
  • Software Delivery at Scale: Centralized Jenkins Pipeline for Optimal Efficiency
  • Traditional Testing and RAGAS: A Hybrid Strategy for Evaluating AI Chatbots
  • Manual Sharding in PostgreSQL: A Step-by-Step Implementation Guide
  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.3K 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, DZone MVB. 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?
  • Apache Doris vs Elasticsearch: An In-Depth Comparative Analysis
  • Doris vs Elasticsearch: A Comparison and Practical Cost Case Study
  • Managing AWS Managed Microsoft Active Directory Objects With AWS Lambda Functions

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!