我正在尝试将具有特定名称的文件移动到另一个文件夹。代码一次只移动一个文件我想一次移动所有文件。
def p1= folderpath1
def p2= folderpath2
def d= new File(p2)
def filesubstr= "hello"
def filepattern= ~/${filesubstr}/
def findfile=
{
if(filepattern.matcher(it.name).find()) {
it.renameTo(p2)
}
d.eachFileRecurse(findfile)
每次我都必须指定一个新的文件名来移动文件。我不明白为什么会发生这种事。
def p2= 'E:\xyz\newfile1'
在一个文件移动后,我必须再次指定新的文件名
def p2= 'E:\xyz\newfile2'
实现这一点的一种方法是在groovy发行版中包含AntBuilder
。
以下代码:
def ant = new AntBuilder()
ant.move(todir: 'targetfolder', overwrite: true, force: true, flatten: false) {
fileset(dir: 'sourcefolder', includes: '**/foo*')
regexpmapper(from: '(.*)foo(.*)', to: '\1bar\2', handledirsep: true)
}
以及以下用于CCD_ 2和CCD_ 3的目录结构:
─➤ tree sourcefolder
sourcefolder
├── baz.txt
├── foo1.txt
├── foo.txt
├── subdirA
│ └── foo2.txt
└── subdirB
└── foo3.txt
2 directories, 5 files
─➤ tree targetfolder
targetfolder
0 directories, 0 files
─➤
执行代码时会产生以下结果:
─➤ groovy solution.groovy
[move] Moving 4 files to targetfolder
─➤ tree sourcefolder
sourcefolder
├── baz.txt
├── subdirA
└── subdirB
2 directories, 1 file
─➤ tree targetfolder
targetfolder
├── bar1.txt
├── bar.txt
├── subdirA
│ └── bar2.txt
└── subdirB
└── bar3.txt
2 directories, 4 files
─➤
换句话说,只移动匹配的文件,并使用在regexmapper
的from
和to
属性中指定的regex模式重命名移动的文件。