Copy Files/Folders from one location to another in Groovy

21 / Sep / 2012 by Vishal Sahu 3 comments

It is normally difficult to copy file/folders from one location to another. In my recent Grails Development project, i successfully achieved this. I had to copy files/folders from one location to another on file system. I searched about it and came across a cool method to copy files or directories from one location to another.

We can simply copy files, directories, exclude particular files as we have good control in it. Below is the code which explains how to use it.

Copy directory to another directory :-


        String sourceDir = SOURCE_DIR_PATH
        String destinationDir = DESTINATION_DIR_PATH
        new AntBuilder().copy(todir: destinationDir) {
            fileset(dir: sourceDir)
        }

This method will copy the source directory to the destination directory with all the internal data in the same structure.

Suppose if we want to exclude some particular file(s), then we can easily provide that file name or the common pattern of those files as mentioned in the example.

Copy directory with excluding some files :-

      String sourceDir = SOURCE_DIR_PATH
      String destinationDir = DESTINATION_DIR_PATH

      new AntBuilder().copy(todir: destinationDir) {
           fileset(dir : sourceDir) {
                 exclude(name:"*.java")
      }
   }

The above code will not copy the files which have an extension .java

Now if i want to copy any particular file, then there is other method to copy it as given below.

Copy files from one directory to another :-


        String sourceFilePath = SOURCE_FILE_PATH
         String destinationFilePath = DESTINATION_FILE_PATH
         (new AntBuilder()).copy(file: sourceFilePath, tofile: destinationFilePath)

This method will copy the provided file to the destination location.

This worked for me. Hope it helps.

Tag -

Grails Groovy
FOUND THIS USEFUL? SHARE IT

comments (3)

  1. Pramod

    Hi,
    Do we need to import any class for this. Runnning above code in groovy script in soap ui failed. Thanking you in anticipation.

    Reply
  2. Suresh

    Hi Vishal,

    can you please help me on to develop groovy script for accepting parameters( Src dir and dest dir and files / folders and operations) dynamically to do copy/move files and folders from src dir to destination dir and again copy back to src dir after renaming files / folders.

    Thanks,

    Suresh.

    Reply

Leave a comment -