请帮忙,这样我就不会扯头发了...
我需要使用从 XML 获取数据的 groovy 将文件夹 A 简单地复制到文件夹 B。我必须使用 XMLSlurper 或 XMLParser
就是这样-
println "Start"
def Folders = new XmlSlurper().parse(new File("CopyParams.xml"))
Folders.Folder.each
{
it.DirectoryToCopy.each
{
println "Copying ${it.@source} into folder ${it.@target}"
new AntBuilder().copy (
todir: "${it.@target}")
{
fileset(
dir: "${it.@source}" )
}
}
}
println "End"
System.exit(0)
然后我得到——
> Copying C:TempGroovySource_Folders into folder C:TempGroovyTarget_Foler
Caught: groovy.lang.MissingFieldException: No such field: source for class: org.codehaus.groovy.runtime.NullObject
groovy.lang.MissingFieldException: No such field: source for class: org.codehaus.groovy.runtime.NullObject
at testCopy$_run_closure1_closure2_closure3.doCall(testCopy.gvy:14)
at testCopy$_run_closure1_closure2_closure3.doCall(testCopy.gvy)
at testCopy$_run_closure1_closure2.doCall(testCopy.gvy:11)
at testCopy$_run_closure1.doCall(testCopy.gvy:7)
at testCopy.run(testCopy.gvy:5)
我尝试在复制之前使用 -
String src = ${it.@source[0]}
String dst = ${it.@target[0]}
或
String src = new XmlNodePrinter().print(${it.@source})
String dst = new XmlNodePrinter().print(${it.@target})
然后我得到——
> Copying C:TempGroovySource_Folders into folder C:TempGroovyTarget_Foler
Caught: groovy.lang.MissingMethodException: No signature of method: testCopy.$() is applicable for argument types: (testCopy$_run_
closure1_closure2_closure3) values: [testCopy$_run_closure1_closure2_closure3@1b06cab]
Possible solutions: is(java.lang.Object), run(), run(), any(), any(groovy.lang.Closure), use([Ljava.lang.Object;)
groovy.lang.MissingMethodException: No signature of method: testCopy.$() is applicable for argument types: (testCopy$_run_closure1
_closure2_closure3) values: [testCopy$_run_closure1_closure2_closure3@1b06cab]
Possible solutions: is(java.lang.Object), run(), run(), any(), any(groovy.lang.Closure), use([Ljava.lang.Object;)
at testCopy$_run_closure1_closure2.doCall(testCopy.gvy:11)
at testCopy$_run_closure1.doCall(testCopy.gvy:7)
at testCopy.run(testCopy.gvy:5)
我也尝试使用FileUtils,但得到了更多无法理解的错误
我做错了什么?
如果我使用"XMLParser"会更好吗?
谢谢伊
当然,有多种选项/方法可以将文件夹的内容复制到另一个文件夹。
最简单的方法是使用 FileUtils.copyDirectory()
,内置于 Java 中,如这篇 SO 帖子中所述:将整个目录内容复制到另一个目录?
或者,您可以使用Java的"Files.copy",如下所述:http://docs.oracle.com/javase/tutorial/essential/io/copy.html
import static java.nio.file.StandardCopyOption.*;
...
Files.copy(source, target, REPLACE_EXISTING);
您可以使用 AntBuilder
,这是您在示例中尝试的。您根本不需要使用XMLSlurper
。 AntBuilder
能够在不处理单个文件的情况下复制整个文件夹(或者可以过滤掉文件,即通过扩展名(。例如:
String sourceDir = SOURCE_DIR_PATH
String destinationDir = DESTINATION_DIR_PATH
new AntBuilder().copy(todir: destinationDir) {
fileset(dir : sourceDir) {
exclude(name:"*.java")
}
或者没有过滤,只需:
new AntBuilder().copy(todir: destinationDir)
在同事的帮助下找到了答案——
将你从XMLSlurper获得的变量声明为字符串应该带有"def">
def sourceDir = "${it.@source}"
def destinationDir = "${it.@target}"