如何在Groovy中复制文件 [英] How to copy files in Groovy

查看:1095
本文介绍了如何在Groovy中复制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


$ b

1



我需要在Groovy中复制一个文件,并看到了一些在网络上实现它的方法:

  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<<是
}
}

4

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

第四种方式对我来说似乎最清洁,因为我不确定它有多好是否使用AntBuilder以及它有多沉重,我看到一些人报告了Groovy版本更改的问题。
第二种方式取决于操作系统,第三种方式可能效率不高。



在Groovy中有没有像第4条语句那样复制文件的东西,还是应该使用Java来处理它?<​​b>

解决方案

如果你有Java 7,我肯定会跟着

  Path source = ... 
路径目标= ...
Files.copy(源,目标)

使用 java.nio。 file.Path 类,它可以使用符号链接和硬链接。从 java.nio.file.Files


该类完全由静态方法组成,它们对
文件,目录或其他类型的文件进行操作。在大多数情况下,这里定义的
方法将委托给关联的文件系统
提供程序来执行文件操作

。 $ b

就像参考资料:

使用Groovy将文件从一个文件夹复制到另一个文件夹



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



我的第二个选项是 ant 任务,其中 AntBuilder


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?

解决方案

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.

这篇关于如何在Groovy中复制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆