File renameTo() method in Java with examples
Last Updated :
28 Jan, 2019
The renameTo() method is a part of File class. The renameTo() function is used to rename the abstract path name of a File to a given path name. The function returns true if the file is renamed else returns false
Function Signature:
public boolean renameTo(File destination)
Syntax:
file.renameTo(File destination)
Parameters: The function requires File object destination as parameter, the new abstract path name of the present file.
Return Value: The function returns boolean data type. The function returns true the file is renamed else returns false
Exception: This method throws following exceptions:
- Security Exception if the method does not allow write operation of the abstract pathnames.
- NullPointerException if the destination filename is null.
Below programs will illustrate the use of renameTo() function:
Example 1: Try to rename the file program.txt to program1.txt
import java.io.*;
public class GFG {
public static void main(String args[])
{
File f = new File( "F:\\program.txt" );
File dest = new File( "F:\\program1.txt" );
if (f.renameTo(dest)) {
System.out.println( "File is renamed" );
}
else {
System.out.println( "File cannot be renamed" );
}
}
}
|
Output:
File is renamed
Example 2: Try to rename “program1.txt” to “prog.txt”, “prog.txt” is a existing file in the f: drive .
import java.io.*;
public class GFG {
public static void main(String args[])
{
File f = new File( "F:\\program1.txt" );
File dest = new File( "F:\\prog.txt" );
if (f.renameTo(dest)) {
System.out.println( "File is renamed" );
}
else {
System.out.println( "File cannot be renamed" );
}
}
}
|
Output:
File cannot be renamed
The programs might not run in an online IDE. please use an offline IDE and set the path of the file
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...