在DefaultTask类中复制并重命名文件?

时间:2015-04-10 08:11:49

标签: java groovy gradle

我想复制srcDir中名称中包含$$的所有文件。如果文件是例如:

x$$y.java

我想创建该文件的副本并将其命名为x$y.java

class MyTask extends DefaultTask {

@InputDirectory File srcDir

@TaskAction
def task() {
  def srcFiles = project.files(project.fileTree(dir: srcDir)).getFiles()
  srcFiles.each { file ->  
        if (file.name.contains("\$\$")) {
           // TODO copy file and rename it to the same name with one dollar sign in the middle

        }
  }
}
}

如何在自定义任务类中复制和重命名文件?

2 个答案:

答案 0 :(得分:4)

尝试:

@TaskAction
def task() {
   project.copy {
      from(project.fileTree(dir: srcDir).files) {
         include {
           it.file.name.contains('$$')
         }
      }
      into('somewhere')
      rename { name ->
         name.replace('$$', '$')
      }
   }
} 

答案 1 :(得分:0)

您可以使用Files类:

if (file.name.contains("\$\$")) {
 // TODO copy file and rename it to the same name with one dollar sign in the middle
  String newFilePath = file.getParent()+"\\"+ "YOUR NEW File"; // use separator which you want  
  File newFile = new File(newFilePath);
  Files.copy(file.toPath(), newFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
}

有关更多选项,请参阅StandardCopyOption