Grails Cookbook - A collection of tutorials and examples

Groovy Copy File Examples

When writing batch programs, it is common to write code to copy files from one directory to another. Here are examples on how to Copy Files in Groovy.

Groovy Copy Text File

Here is a code in Groovy that copies a text file:

class FileExample {
   static void main(String[] args) {
      def src = new File('c:/temp/src.txt')
      def dst = new File('c:/temp/dst.txt')
      dst << src.text
   }
}

We can shorten this to:

new File('c:/temp/dst.txt') << new File('c:/temp/src.txt').text

Groovy Copy Binary File

If the file we wish to copy is not text, like zip archive or executable, here is a sample code to copy a binary file in Groovy:

class FileExample {
   static void main(String[] args) {
      def src = new File('c:/temp/src.zip')
      def dst = new File('c:/temp/dst.zip')
      dst << src.bytes
   }
}

Note that this can be potentially slow and memory hungry, as this code loads the entire file to memory before copying.

Again, We can shorten this to:

new File('c:/temp/dst.zip') << new File('c:/temp/src.zip').bytes

Here is another example of copying files in Groovy using streams.

class FileExample {
   static void main(String[] args) {
      def srcStream = new File('/home/jon/xxx.zip').newDataInputStream()
      def dstStream = new File('/home/jon/xxx2.zip').newDataOutputStream()
      dstStream << srcStream
      srcStream.close()
      dstStream.close()
   }
}