有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我想复制我的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) 个答案

  1. # 1 楼答案

    试试看:

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

    可以使用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