2

増分番号を追加して、ファイルがすでに存在する場合は、ファイルを再帰的にチェックして名前を変更するにはどうすればよいですか?

以下の関数を作成しましたが、例外が発生します

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

1 に答える 1

3

あなたがしようとしていること:

f = checkForExistenceAndRename(newFilePath,false)

はどこfにありますかFile。しかし、あなたの関数は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
  }
}
于 2012-11-02T11:12:36.743 に答える