Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy files in Groovy

Tags:

groovy

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

1

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

2

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

3

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

4

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?

like image 213
Roman Goyenko Avatar asked Feb 26 '14 17:02

Roman Goyenko


People also ask

How do I save a Groovy file?

To save a Groovy script that is currently open in the Groovy editor: From the Tools Main menu select Groovy > Save Script or Save Script As.


3 Answers

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

http://groovyconsole.appspot.com/view.groovy?id=8001

My second option would be the ant task with AntBuilder.

like image 128
jalopaba Avatar answered Oct 12 '22 02:10

jalopaba


If you are doing this in code, just use something like:

new File('copy.bin').bytes = new File('orig.bin').bytes

If this is for build-related code, this would also work, or use the Ant builder.

Note, if you are sure the files are textual you can use .text rather than .bytes.

like image 45
cjstehno Avatar answered Oct 12 '22 00:10

cjstehno


If it is a text file, I would go with:

  def src = new File('src.txt')
  def dst = new File('dst.txt')
  dst << src.text
like image 12
jdevora Avatar answered Oct 12 '22 00:10

jdevora