groovy多文件重命名:不工作

groovy多文件重命名:不工作,groovy,Groovy,我试图实现一个小任务,即以特定方式重命名目录中的多个CSV文件。代码非常简单,但不确定出于什么原因它根本不显示任何输出,这两项工作都没有完成。有人能看看我的代码,让我知道我哪里出错了吗 import static groovy.io.FileType.* import static groovy.io.FileVisitResult.* try{ def workDir = 'C:\\Users\\myUser\\Desktop\\testFiles' def userInputFileNam

我试图实现一个小任务,即以特定方式重命名目录中的多个CSV文件。代码非常简单,但不确定出于什么原因它根本不显示任何输出,这两项工作都没有完成。有人能看看我的代码,让我知道我哪里出错了吗

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
评论?
Groovy版本:
2.4.15

您正在混合$variableName和variableName

  it.renameTo(new File(${userInputFileName} + "_" + ${meds} + "_" + file.getName(), file.getName()))
$variableName用于字符串(GString)类型的情况。下面的方法应该有效

 it.renameTo(new File(userInputFileName + "_${meds}_" + file.getName(), file.getName()))

这对我很有用,使用
数据
作为目录。请注意,为了清晰起见,它将一些行分隔开:

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()
    }
}

你要求评论:

你的代码中有很多错误。不是常规的错误。编程错误

以下是工作代码:

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)
}

谢谢你。欣赏批评家;我将努力改进你的建议。