14

I want to do a simple file rename in a gradle task. I have a jar called project-1.5.jar under the folder src and I want the jar to be renamed to just project.jar

So,

project/project-1.5.jar to project/project.jar using gradle

Any ideas are much appreciated.

George Cimpoies
  • 884
  • 2
  • 14
  • 26
  • Possible duplicate of [Gradle zip: how to include and rename one file easily?](https://stackoverflow.com/questions/44997196/gradle-zip-how-to-include-and-rename-one-file-easily) – Ben Watson Mar 21 '18 at 09:34

4 Answers4

18

The rename method should do the trick.

task renameArtifacts (type: Copy) {
    from ('project/')
    include 'project-1.5.jar'
    destinationDir file('project/')
    rename 'project-1.5.jar', "project.jar"
}
Chathuranga Chandrasekara
  • 20,548
  • 30
  • 97
  • 138
  • 2
    rename 'project-1.5.jar', "project.jar" , can we make it generic by using something like rename 'project*.jar', "project.jar" - However this is not working can someone tell me alternative – ShankPossible Dec 27 '19 at 10:26
  • I could be wrong, but wouldn't this do a _copy_ instead of a _rename_. The question specifically asked for a way to _rename_ files. In any case, a copy will suffice for most use cases. – DBear Jul 07 '22 at 00:58
6

For me this worked - does not leave source files (no duplications).

task pdfDistributions(type: Sync) {
    from('build/asciidoc/pdf/docs/asciidoc/')
    into('build/asciidoc/pdf/docs/asciidoc/')
    include '*.pdf'
    rename { String filename ->
        filename.replace(".pdf", "-${project.version}.pdf")
    }
}
2

Gradle allows to call ant tasks from your task implementation. It makes moving files as easy as

ant.move(file:'oldFile.txt', tofile:'newfile.txt')
dpolivaev
  • 494
  • 3
  • 12
  • This is useful when you need to rename files but not having to use a "copy" task say, in a function or as a step within another type of/custom task. Should be a native way to do this (unless I'm missing it). – galaxis Mar 23 '21 at 16:30
0

Late .. but gradle provide project.file('xxx').renameTo('zzz')

Greg Henry
  • 61
  • 6
  • While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Yunnosch Aug 05 '23 at 08:18