groovy - 如何使用 groovy 递归检查文件是否存在并重命名(如果存在)?

标签 groovy

如果文件已经存在,如何通过附加一些递增数字来递归检查和重命名该文件?

我编写了以下函数,但它给了我一个异常(exception)

org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'E:\Projects\repo1\in_conv1.xml' with class 'java.lang.String' to class 'java.io.File'

代码

//newFilePath = E:\Projects\repo1\old\testcustprops.xml
String newFilePath = checkForExistenceAndRename(newFilePath,false)

private String checkForExistenceAndRename(String newFilePath, boolean flag){
    File f = new File(newFilePath)
    if(!flag){
        if(f.exists()){
            //renaming file
            newFilePath=newFilePath[0..-5]+"_conv${rename_count++}.xml"
            f = checkForExistenceAndRename(newFilePath,false)
        }
        else 
            f = checkForExistenceAndRename(newFilePath,true)
    }
    else
        return newFilePath      
}

最佳答案

您正在尝试执行以下操作:

f = checkForExistenceAndRename(newFilePath,false)

其中f是一个文件。但是你的函数返回一个String

不确定它是否有效(我没有测试你的功能),但你可以尝试:

private String checkForExistenceAndRename(String newFilePath, boolean flag){
    File f = new File(newFilePath)
    if(!flag){
        if(f.exists()){
            //renaming file
            newFilePath = newFilePath[0..-5]+"_conv${rename_count++}.xml"
            newFilePath = checkForExistenceAndRename(newFilePath,false)
        }
        else 
            newFilePath = checkForExistenceAndRename(newFilePath,true)
    }
    return newFilePath      
}

此外,无需使用递归...

为什么不这样做:

private String getUniqueName( String filename ) {
  new File( filename ).with { f ->
    int count = 1
    while( f.exists() ) {
      f = new File( "${filename[ 0..-5 ]}_conv${count++}.xml" )
    }
    f.absolutePath
  }
}

关于groovy - 如何使用 groovy 递归检查文件是否存在并重命名(如果存在)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13194033/

相关文章:

Java StampedLock : what happens to writer while someone is reading

groovy - 如何防止使用默认构造函数?

parsing - groovy更新配置文件

java - 在 maven 中运行 groovy 脚本与在 IDE 中运行时显示错误

groovy - 为什么键和值相同时 `java.util.LinkedHashMap` 不相等?

java - 如何在 Java/Groovy 中使用 getAt() 函数?

java - 将 groovy 与 stripes web 框架结合使用

git - gradle:groovy命令行-grep

grails - 如何在 grails 中安装和使用 httpbuilder 插件

spring - 使用 Grails/Groovy 阅读收件箱?