如果文件已经存在,如何通过附加一些递增数字来递归检查和重命名该文件?
我编写了以下函数,但它给了我一个异常(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/