Groovy Goodness: Extra Methods for NIO Path
Join the DZone community and get the full member experience.
Join For FreeGroovy 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.
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.
Comments