Roman Goyenko Roman Goyenko - 1 year ago 262
Groovy Question

How to copy files in Groovy

I need to copy a file in Groovy and saw some ways to achieve it on the web:


new AntBuilder().copy( file:"$sourceFile.canonicalPath",


command = ["sh", "-c", "cp src/*.txt dst/"]
Runtime.getRuntime().exec((String[]) command.toArray())


destination.withDataOutputStream { os->
source.withDataInputStream { is->
os << is


import java.nio.file.Files
import java.nio.file.Paths
Files.copy(Paths.get(a), Paths.get(b))

The 4th way seems cleanest to me as I am not sure how good is it to use AntBuilder and how heavy it is, I saw some people reporting issues with Groovy version change.
2nd way is OS dependent, 3rd might not be efficient.

Is there something in Groovy to just copy files like in the 4th statement or should I just use Java for it?

Answer Source

If you have Java 7, I would definitely go with

Path source = ...
Path target = ...
Files.copy(source, target)

With the java.nio.file.Path class, it can work with symbolic and hard links. From java.nio.file.Files:

This class consists exclusively of static methods that operate on files, directories, or other types of files. In most cases, the methods defined here will delegate to the associated file system provider to perform the file operations.

Just as references:

Copy files from one folder to another with Groovy

My second option would be the ant task with AntBuilder.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download