我需要在Groovy中复制一个文件,并看到一些方法在Web上实现它:
1
new AntBuilder().copy( file:"$sourceFile.canonicalPath",
tofile:"$destFile.canonicalPath")
Run Code Online (Sandbox Code Playgroud)
2
command = ["sh", "-c", "cp src/*.txt dst/"]
Runtime.getRuntime().exec((String[]) command.toArray())
Run Code Online (Sandbox Code Playgroud)
3
destination.withDataOutputStream { os->
source.withDataInputStream { is->
os << is
}
}
Run Code Online (Sandbox Code Playgroud)
4
import java.nio.file.Files
import java.nio.file.Paths
Files.copy(Paths.get(a), Paths.get(b))
Run Code Online (Sandbox Code Playgroud)
第四种方式对我来说似乎最干净,因为我不确定使用AntBuilder有多好以及它有多重,我看到有些人报告了Groovy版本更改的问题.第二种方式是依赖操作系统,第三种方式可能效率不高
Groovy中是否有东西可以像第4个语句那样复制文件,或者我应该只使用Java?
jal*_*aba 50
如果你有Java 7,我一定会去
Path source = ...
Path target = ...
Files.copy(source, target)
Run Code Online (Sandbox Code Playgroud)
使用java.nio.file.Path类,它可以使用符号链接和硬链接.来自java.nio.file.Files:
此类仅包含对文件,目录或其他类型文件进行操作的静态方法.在大多数情况下,此处定义的方法将委派给关联的文件系统提供程序以执行文件操作.
正如参考:
http://groovyconsole.appspot.com/view.groovy?id=8001
我的第二个选择是ant任务AntBuilder.
小智 12
如果是文本文件,我会选择:
def src = new File('src.txt')
def dst = new File('dst.txt')
dst << src.text
Run Code Online (Sandbox Code Playgroud)
cjs*_*hno 11
如果你在代码中这样做,只需使用如下:
new File('copy.bin').bytes = new File('orig.bin').bytes
Run Code Online (Sandbox Code Playgroud)
如果这是与构建相关的代码,这也可以,或使用Ant构建器.
请注意,如果您确定文件是文本的,则可以使用.text而不是.bytes.
要附加到现有文件:
def src = new File('src.txt')
def dest = new File('dest.txt')
dest << src.text
Run Code Online (Sandbox Code Playgroud)
要覆盖文件是否存在:
def src = new File('src.txt')
def dest = new File('dest.txt')
dest.write(src.text)
Run Code Online (Sandbox Code Playgroud)
我更喜欢这样:
def file = new File("old.file")
def newFile = new File("new.file")
Files.copy(file.toPath(), newFile.toPath())
Run Code Online (Sandbox Code Playgroud)