One of the features of File class is the renameTo method and in this tutorial we will see how this method can be used.

Renaming folders

renameTo() method is equally applicable in files and folders.As for example consider the case where we have a folder named namedFolder and we rename it as renamedFolder:

import java.io.File;

public class FileRenaming {
    
    public static void main(String args[]){
        File directory=new File("C:\\namedFolder");
        boolean renamed=directory.renameTo(new File("C:\\renamedFolder"));
        System.out.println("RENAME:"+renamed);
    }
}

Renaming Files

File renaming can be achieved the same way as in folder renaming.For example let's say we have a file named namedFile.txt and we need to rename it as renamedFile.txt:

public class FileRenaming {
    
    public static void main(String args[]){
        File directory=new File("C:\\namedFile.txt");
        boolean renamed=directory.renameTo(new File("C:\\renamedFile.txt"));
        System.out.println("RENAME:"+renamed);
    }
}

Some things good to note is that if a file is renamed with the file extention changed renameTo() will return false.RenameTo() will also return false if the path of the renamed file is different.