El siguiente programa muestra los contenidos de un directorio filtrados según una regexp. Siguen varias ejecuciones. Primero sin argumentos:
generaciondecodigos@nereida:~/src/groovy/files$ ./ls.groovy slurpFile.groovy writeFile.groovy env.groovy .readfile.groovy.swp ls.groovy readfile.groovy .renamefiles.groovy.swp .svn writeEuro.groovy myFile.txtAhora pasamos como argumento una expresión regular:
generaciondecodigos@nereida:~/src/groovy/files$ ./ls.groovy 'groovy$' slurpFile.groovy writeFile.groovy env.groovy ls.groovy readfile.groovy writeEuro.groovyTambién podemos pasar un argumento adicional referenciando un directorio. En este caso se listarán los ficheros en dicho directorio que casan con la expresión regular:
generaciondecodigos@nereida:~/src/groovy/files$ ./ls.groovy 'jar$' /tmp/ groovy-groosh-0.3.5.jar
The method public void eachFile(Closure)
invokes the closure for each
'child' file in this 'parent' folder/directory.
Both regular files and subfolders/subdirectories are processed.
generaciondecodigos@nereida:~/src/groovy/files$ cat -n ls.groovy 1 #!/usr/bin/env groovy 2 if (args.length > 1) { 3 regexp = args[0] 4 dirName = args[1] 5 } 6 else if (args.length > 0) { 7 regexp = args[0] 8 dirName = '.' 9 } 10 else { 11 regexp = '.*' 12 dirName = '.' 13 } 14 15 new File(dirName).eachFile() { file -> 16 if (file.getName() =~ regexp) { 17 println file.getName() 18 } 19 }
La clausura recibe un objeto File.
The method public String getName()
returns the name of the file or directory denoted by this abstract
pathname. This is just the last name in the pathname's name
sequence. If the pathname's name sequence is empty, then the empty
string is returned.
El ejemplo anterior puede reescribirse usando el método
public void eachFileMatch(Object, Closure)
Invokes the closure for each file whose name (file.name
) matches the givennameFilter
in the given directory - calling theObject#isCase
method to determine if a match occurs. This method can be used with different kinds of filters like regular expressions, classes, ranges etc. Both regular files and subdirectories are matched.
groovy:000> x = new File('.').eachFileMatch(~/s.*\.groovy/) { println it } ./slurpFile.groovy ./slurpFile2.groovy ./socket.groovy ./stdin.groovy ===> null
El operador ~
aplicado a una cadena produce el objeto Pattern
que representa el reconocedor del lenguaje definido por la expresión regular
especificada en la cadena.
The method public void eachFileRecurse(Closure)
invokes the
closure for each descendant file in this directory. Sub-directories
are recursively searched in a depth-first fashion. Both regular
files and subdirectories are passed to the closure.
Ejemplo:
groovy:000> x = new File('.').eachFileRecurse() { if (it =~ /[ao]n\.groovy$/) println it } ./objects/DynamicMethodCreation.groovy ./objects/dynamicmethodnamecreation.groovy ./overloading/Numberscohercioncomparison.groovy ./strings/scan.groovy ./strings/StringToBoolean.groovy ===> null