Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

How to search for files with groovy util?


Asked by Chaya Glover on Dec 04, 2021 Groovy



The groovy.util package contains the FileNameFinder and FileNameByRegExFinder classes. We can use the FileNameFinder classe to search recursively for files in a directory with ANT fileset pattern conventions. With the FileNameByRegExFinder we use regular expressions to define the file patterns.
Keeping this in consideration,
Groovy provides multiple methods to do this. For example you can perform something on all files of a directory: dir.eachFile { file -> println file.name } dir.eachFileMatch(~/.*.txt/) { file ->
Accordingly, There are many Groovy IO methods like readLine and eachLine available for reading files line by line. Let's start with the File.withReader method. It creates a new BufferedReader under the covers that we can use to read the contents using the readLine method. For example, let's read a file line by line and print each line.
In addition,
While you could use standard Java code in Groovy to deal with those, Groovy provides much more convenient ways to handle files, streams, readers, … In particular, you should take a look at methods added to: the java.io.File class : http://docs.groovy-lang.org/latest/html/groovy-jdk/java/io/File.html
And,
In our case, the value of articles is a groovy.util.NodeList instance, which is a wrapper class for a collection of Node s. The NodeList extends the java.util.ArrayList class, which provides extraction of elements by index. To obtain a string value of a Node, we use groovy.util.Node#text ().