Home » Java programming language

Java File Class boolean renameTo(File new_pathname) method with Example

Java File Class boolean renameTo(File new_pathname) method: Here, we are going to learn about the boolean renameTo(File new_pathname) method of File class with its syntax and example.
Submitted by Preeti Jain, on July 15, 2019

File Class boolean renameTo(File new_pathname)

  • This method is available in package java.io.File.renameTo(File new_pathname).
  • This method is used to rename or change the pathname of a file to a given parameter (new_pathname) of the method.
  • In this method, we need to remember one thing if we try to change the pathname of a file to a given pathname of the file and if given pathname of a file is already exists then it is not allowed to rename the file is of the same name.
  • The return type of this method is Boolean it returns true if file pathname is renamed successfully else return false that's is file pathname is not renamed.

Syntax:

    boolean renameTo(File new_pathname){
    }

Parameter(s):

We pass only one object as a parameter in the method of the File (i.e. File object new_Pathname).

Return value:

The return type of this method is Boolean, it returns true if the pathname is successfully renamed if and only if given pathname of a file does not already exist and else return false that's is given pathname of a file already exists.

Java program to demonstrate example of renameTo() method

// import the File class because we will use File class methods
import java.io.File;

// import the Exception class because it may raise an 
// exception when working with files
import java.lang.Exception;

public class RenameFile {
    public static void main(String[] args) {
        try {
            // Specify the path of file and we use double slashes to 
            // escape '\' character sequence for windows otherwise 
            // it will be considerable as url.

            File file1 = new File("C:\\Users\\computer clinic\\OneDrive\\Articles\\myjava.txt");
            File file2 = new File("C:\\Users\\computer clinic\\OneDrive\\Articles\\myjava1.txt");

            // By using renameTo(file2) method we are renaming the file 
            // myjava.txt to myjava1.txt and it returns true because given 
            // filename myjava1.txt is not already exists.
            if (file1.renameTo(file2))
                System.out.println("File is renamed Successfully from myjava.txt to myjava1.txt");
            else
                System.out.println("File is not renamed Successfully from myjava.txt to myjava1.txt");

        } catch (Exception e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}

Output

D:\Programs>javac RenameFile.java

D:\Programs>java RenameFile
File is renamed Successfully from myjava.txt to myjava1.txt



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.