Search code examples
javafilerenaming

Renaming a file with a string from a file of different extension


I need to rename an .afp file with name of .txt file. I have stumbled across numerous "solutions" while trying to get this thing working and nothing helped.

Let's say I have a txt file in C:/test/a/Mytes t.txt and I want to rename .afp file which is in C:/files/b/Testf ile.afp. This is what I'm trying to do (according to solutions found on this site) and it isn't working. I cut the extension of .txt file and get only file name:

String fileNameNoExt=fileName.substring(0, fileName.lastIndexOf('.'));
//fileName is .txt file name
File file = new File(afpSRC, afpName);
file.renameTo(new File(afpSRC, fileNameNoExt + ".afp"));

afpSRC contains Path to folder in which .afp file is located and afpName is the name of the file.

Can anyone tell me why this isn't working and .afp file name remains the same?


Solution

  • Probably because File file = new File(afpSRC, afpName); doesn't refer a existing file.

    I suspect that either afpSRC is not the parent path or afpName is not the filename. Or both ?

    To debug you should check that the file exists first.
    If it doesn't exist, throw an exception.
    Besides in any way (debug and final code) you should check the returned value by renameTo() and handle it consequently.

    Here is a sample code :

    String fileNameNoExt=fileName.substring(0, fileName.lastIndexOf('.'));
    //fileName is .txt file name
    File file = new File(afpSRC, afpName);
    if (!file.exists()){
       throw new RuntimeException("file not found = " + file);
    }
    
    boolean isRenamed = file.renameTo(new File(afpSRC, fileNameNoExt + ".afp"));
    System.out.println("isRenamed = " + isRenamed);
    if (!isRenamed){
       // handle the problem
    }