Reputation: 840
I am trying to achieve a small task of renaming multiple CSV files present in a directory in a specific fashion. The code is pretty simple but not sure for what reason it doesn't show any output at all, neither the job gets done. Can someone please take a look into my code and let me know where I went wrong?
import static groovy.io.FileType.*
import static groovy.io.FileVisitResult.*
try{
def workDir = 'C:\\Users\\myUser\\Desktop\\testFiles'
def userInputFileName = "ppi"
def meds = "11223344"
new File("${workDir}").eachFileRecurse(FILES) {
if(it.name.endsWith('.csv')) {
println(it)
it.renameTo(new File(${userInputFileName} + "_" + ${meds} + "_" + file.getName(), file.getName()))
}
}
}
catch(Exception e){
println(e)
}
Existing File Name: file-234-ggfd-43445fh.csv
To be converted file name: ${userInputFileName}_${meds}_file-234-ggfd-43445fh.csv
Comments?
Groovy version: 2.4.15
Upvotes: 1
Views: 1055
Reputation: 18459
You are mixing $variableName and variableName.
it.renameTo(new File(${userInputFileName} + "_" + ${meds} + "_" + file.getName(), file.getName()))
The $variableName is meant for using in String ( GString) type situation. Following should work.
it.renameTo(new File(userInputFileName + "_${meds}_" + file.getName(), file.getName()))
Upvotes: 1
Reputation: 4811
You asked for comments:
There were many mistakes in your code. Not groovy mistakes. Programming mistakes.
Here's the working code:
import static groovy.io.FileType.*
import static groovy.io.FileVisitResult.*
try {
def workDir = 'C:/Users/myUser/Desktop/testFiles' as File
def userInputFileName = "ppi"
def meds = "11223344"
workDir.eachFileRecurse(FILES) { file ->
if (file.name.endsWith('.csv')) {
println(file)
def target = new File(workDir, "${userInputFileName}_${meds}_${file.name}")
file.renameTo(target)
assert target.exists()
assert !file.exists()
}
}
}
catch (Exception e) {
println(e)
}
Upvotes: 1
Reputation: 24468
This works for me, using data
as a directory. Note that it breaks some lines apart for clarity:
import static groovy.io.FileType.*
import static groovy.io.FileVisitResult.*
def workDir = 'data'
def userInputFileName = "ppi"
def meds = "11223344"
new File("${workDir}").eachFileRecurse(FILES) {
if (it.name.endsWith('.csv')) {
println(it)
def destPath = "${it.parent}${File.separator}${userInputFileName}_${meds}_${it.name}"
def dest = new File(destPath)
it.renameTo(dest)
assert dest.exists()
assert ! it.exists()
}
}
Upvotes: 1