Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Java | Renaming a file

  • Difficulty Level : Easy
  • Last Updated : 26 Mar, 2018

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

Following is the declaration for dest) method:

public boolean renameTo(File dest)


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

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.

// Java program to rename a 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");        
Renamed successfully

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!