如何在Groovy中复制文件 [英] How to copy files in 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
文件,目录或其他类型的文件进行操作。在大多数情况下,这里定义的
方法将委托给关联的文件系统
提供程序来执行文件操作
就像参考资料:
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屋!