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

如何递归检查文件';使用groovy是否存在并重命名(如果存在)?,groovy,Groovy,如果文件已经存在,如何通过追加一些递增的数字来递归地检查和重命名该文件 我写了下面的函数,但它给了我一个例外 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' 代码 您正在尝试执行以下操作: f = checkF

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

我写了下面的函数,但它给了我一个例外

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'
代码

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

f = checkForExistenceAndRename(newFilePath,false)
其中
f
是一个
文件
。但是您的函数返回一个
字符串

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

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

我去掉了您问题中的java标记,因为这是GroovyTanks,您的函数非常小,看起来也很有效
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
  }
}