Friday, April 15, 2011

A quick groovy script to copy file from one folder to another

It quite interesting to use groovy script for simple task as this. Here is an example how can we copy the files from one folder to another...

def sourceDir = "C:\\Source"
def destinationDir = "C:\\Target"


//checking for source directory
def directory = new File("${sourceDir}")
if (!directory.isDirectory()) {
println "The provided directory name ${sourceDir} is NOT a directory."
}


//Clousre
def write = {data, lenth ->
output.write(data, 0, lenth)
}


//Closure
def fileCopyClosure = {
    if(it.canRead()) { //make sure whether you can read it
       def destFolder = new File("${destinationDir}")
          if(!destFolder.exists()) {
              println("Creating new destination directory  [${destFolder}]")
              destFolder.mkdir()
          }


          println "processing ${it.name} from ${it.canonicalPath}"


         def desti = new File("${destinationDir}\\${it.name}")


         //create output stream
         output = desti.newOutputStream()
         it.eachByte(1024, write)
         output.close()


         println "Copy completed${desti.name}"
     }
}
directory.eachFileRecurse(fileCopyClosure)

No comments: