Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Groovy Goodness: Extra Methods for NIO Path

DZone's Guide to

Groovy Goodness: Extra Methods for NIO Path

· Java Zone ·
Free Resource

How do you break a Monolith into Microservices at Scale? This ebook shows strategies and techniques for building scalable and resilient microservices.

Groovy adds a lot of extra methods to the File object to work with the contents or find and filter files in a directory. These methods are now also added to the java.nio.file.Path class since Groovy 2.3.

import java.nio.file.*

final Path newFile = Paths.get('output.txt')
if (Files.exists(newFile)) {
    Files.delete(newFile)
}

// Different ways to add content.
newFile.write 'START'
newFile.write System.getProperty('line.separator')
newFile << 'Just a line of text'
newFile.withWriterAppend { writer ->
    writer.println()
    writer.println 'END'
}
// Read contents.
final Path readFile = Paths.get('output.txt')

assert readFile.readLines().join(';') == 'START;Just a line of text;END'
assert readFile.filterLine { it.contains('text') }.toString().normalize() == 'Just a line of text\n'
// Work with Path objects,
// like with File GDK extensions with
// eachFile, eachDir, eachFileRecursive...
final Path root = Paths.get('.')
def paths = root.eachFileMatch(~/.*\.txt$/) {
    assert it.toFile().name == 'output.txt'
}

Code written with Groovy 2.3.

How do you break a Monolith into Microservices at Scale? This ebook shows strategies and techniques for building scalable and resilient microservices.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}