gpt4 book ai didi

groovy - 如何在 Groovy 中复制文件

转载 作者:行者123 更新时间:2023-12-03 07:30:25 25 4
gpt4 key购买 nike

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

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))

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

Groovy 中是否有某些功能可以像第四条语句中那样复制文件,或者我应该只使用 Java 来实现它?

最佳答案

如果你有 Java 7,我肯定会选择

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

java.nio.file.Path类,它可以使用符号链接(symbolic link)和硬链接(hard link)。来自 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.

仅供引用:

Copy files from one folder to another with Groovy

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

我的第二个选择是使用 AntBuilder 执行 ant 任务。

关于groovy - 如何在 Groovy 中复制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22049395/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com