我试图以一种特定的方式重命名目录中的多个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
发布于 2018-05-25 01:34:14
你把$variableName和variableName混在一起。
  it.renameTo(new File(${userInputFileName} + "_" + ${meds} + "_" + file.getName(), file.getName()))$variableName用于在字符串( GString)类型情况下使用。以下几点应该可行。
 it.renameTo(new File(userInputFileName + "_${meds}_" + file.getName(), file.getName()))发布于 2018-05-25 01:40:45
这对我来说是可行的,使用data作为目录。请注意,为了清晰起见,它将一些线分开:
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()
    }
}发布于 2018-05-25 01:45:45
你征求意见:
您的代码中有许多错误。不是很奇怪的错误。编程错误。
以下是工作代码:
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)
}https://stackoverflow.com/questions/50518670
复制相似问题