Java | Renaming a file

In Java we can rename a file using renameTo(newName) method that belongs to the File class.
Declaration:

Following is the declaration for java.io.File.renameTo(File dest) method:

public boolean renameTo(File dest)

Parameters:

dest – The new abstract pathname for the existing abstract pathname.
Exception:

SecurityException : If a security manager exists and its method denies write access to either the old or new pathnames.

NullPointerException : If parameter destination is null.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to rename a file.
import java.io.File;
  
public class GeeksforGeeks {
    public static void main(String[] args)
    {
        File oldName =
         new File("C:\Users\Siddharth\Desktop\java.txt");
        File newName = 
         new File("C:\Users\Siddharth\Desktop\GeeksforGeeks.txt");
  
        if (oldName.renameTo(newName)) 
            System.out.println("Renamed successfully");        
        else 
            System.out.println("Error");        
    }
}

chevron_right


Renamed successfully


My Personal Notes arrow_drop_up

Lets get started

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.