2012-11-02 59 views
3

如何遞歸檢查和重命名文件,如果它已經存在通過附加一些遞增的數字?如何使用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' 

代碼

//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  
} 
+0

我擺脫了對你的問題的Java標記,因爲這是常規 –

回答

3

你正在嘗試做的:

f = checkForExistenceAndRename(newFilePath,false) 

fFile。但你的函數返回一個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 
    } 
} 
+0

感謝您的功能非常小,看起來太高效 – Ricky

相關問題