Dienstag Feb 09, 2010

why I like groovy

I use groovy more and more often. See this little gem for transforming the charset of a batch of textfiles. Couldn't get a lot simpler. It's basically 6 lines of code:

if(args.length != 4) {
	println "Usage: specify these arguments: input dir, input encoding, output dir, output encoding"
	return
}

def inputDir = new File(args[0])
def inputEncoding = args[1]
def outputDir = new File(args[2])
def outputEncoding = args[3]

assert inputDir.exists(), "${inputDir} must exist"
assert inputDir.canRead(), "${inputDir} must be readable"
assert outputDir.exists(), "${outputDir} must exist"
assert outputDir.canWrite(), "${outputDir} must be writable"

inputDir.eachFileMatch(~/.+\.txt/) { file ->
	def reader = file.newReader(inputEncoding)
	
	def outputFile = new File(outputDir, file.name)
	outputFile.withWriter(outputEncoding) { writer ->
		writer << reader
	}
}
Love it!

Kommentare:

Senden Sie einen Kommentar:
  • HTML Syntax: Eingeschaltet