Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Code to accompany "Parsing files using Groovy closures" on my blog.
package com.octodecillion
import java.nio.file.Files;
/**
* Simple folder walker and file parser.
* <p>
* Dev with Groovy 2.1.6, Java 7, Eclipse 4.3
*
* @author jbetancourt
*
*/
class Gather {
/** test file name with filter, if true, iterate lines
* and collect data via strainer.
* <p>
* @param file the file
* @param filter file name filter
* @param strainer line strainer
* @return List<List<Object>>
*/
static gather(File file, Closure strainer) {
def all = []
file.eachLine{ line ->
def list = strainer(line)
if(list.size){
all << list
}
}
return all
}
/** Gather files in a folder */
static gather(File folder, Closure filter, Closure strainer) {
def all = []
folder.eachFile { file ->
if(filter(file)){
all << gather(file, strainer)
}
}
return all
}
/** Gather files in a folder */
static gatherRecurse(File folder, Closure filter, Closure strainer) {
def all = []
folder.eachFileRecurse {
if(filter(file)){
file.eachLine{ line ->
def list = strainer(line)
if(list.size){
all << list
}
}
}
}
return all
}
/** a test */
static main(args) {
def folder= Files.createTempDirectory("tempFolder")
folder.toFile().deleteOnExit()
def f = Files.createTempFile(folder, "test", ".log")
f.toFile().deleteOnExit()
f.toFile().text =
'''
# test data
20120817 Foo.java
# 2 20120817 Foo.java
2013 Fee.java
'''
def list = Gather.gather(folder.toFile(), { file ->
file.name.matches(/.*\.log/) }) { line ->
def m = line ==~ /^\s*\d{8}\s+\S+\.java.*/
if(m){
return [line]
}
return []
}
assert list.size == 1 // has [[[ 20120817 Foo.java]]]
def result = list[0][0] // [ 20120817 Foo.java]
assert result[0] == ' 20120817 Foo.java'
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.