Rename a File in Java

 Posted On  | Yashwant Chavan 

This Java File API boolean java.io.File.renameTo(File newFile) method is used to rename the file. It is always recommended to check the return value. It helps you to make sure that the rename operation was successful or not. API It returns true when rename is successful, and false if unsuccessful.

Java File renameTo() method syntax

This Java File API boolean java.io.File.renameTo(File newFile) method is used to rename the file. It is always recommended to check the return value. It helps you to make sure that the rename operation was successful or not. API It returns true when rename is successful, and false if unsuccessful.

boolean java.io.File.renameTo(File newFile);
  • Parameters : File newFile The new abstract pathname for the named file
  • Returns: true if and only if the renaming succeeded; false otherwise
  • Throws : It throws SecurityException if a security manager exists and its checkWrite(java.lang.String) method denies write access to either the old or new file objects
  • NullPointerException Throws If parameter newFile is null

Java File Rename Example

package com.technicalkeeda.app;

import java.io.File;

public class JavaFileRenameExample {
    public static void main(String[] args) {
        File oldFile = new File("c:\\oldfile.txt");
        File newFile = new File("c:\\newfile.txt");

        if (oldFile.renameTo(newFile)) {
            System.out.println("Rename Done!!!");
        } else {
            System.out.println("Sorry Unable to Rename!!");
        }
    }

}

Output

Let us compile and execute the above program.

Rename Done!!!


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0336 seconds.