Copy Files/Folders from one location to another in Groovy

21 / Sep / 2012 by Vishal Sahu 5 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 :-

[java]

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

[/java]

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 :-

[java]
String sourceDir = SOURCE_DIR_PATH
String destinationDir = DESTINATION_DIR_PATH

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

[/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 :-

[java]

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

[/java]

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

This worked for me. Hope it helps.

FOUND THIS USEFUL? SHARE IT

Tag -

Grails Groovy

comments (5)

  1. Gaurav Khurana

    Thanks a lot . Your simple code has solved a great problem of ours. We were stuck with the code. Now its working great. Thanks a lot

    Reply
  2. 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
  3. 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 Reply

Your email address will not be published. Required fields are marked *