Java File renameTo() method example

HQ ┬╗ Java Tutorial ┬╗ ┬╗ File ┬╗ renameTo() method example
Java File renameTo() method example 2018-02-16T07:26:40+00:00 renameTo(File dest)


On this document we will be showing a java example on how to use the renameTo(File dest) method of File Class. This method renames the file denoted by this abstract pathname.

Many aspects of the behavior of this method are inherently platform-dependent: The rename operation might not be able to move a file from one filesystem to another, it might not be atomic, and it might not succeed if a file with the destination abstract pathname already exists. The return value should always be checked to make sure that the rename operation was successful.


  • SecurityException – If a security manager exists and its SecurityManager.checkWrite(java.lang.String) method denies write access to either the old or new pathnames
  • NullPointerException – If parameter dest is null

Method Syntax

public boolean renameTo(File dest)

Method Argument

Data Type Parameter Description
File dest The new abstract pathname for the named file

Method Returns

This method returns boolean, true if and only if the renaming succeeded; false otherwise.


Requires Java 1.0 and up

Java File renameTo(File dest) Example

Below is a java code demonstrates the use of renameTo(File dest) method of File class. The example presented might be simple however it shows the behaviour of the renameTo(File dest) method of File class. Basically on this example, two new File instances were created. One is the source file and the other is the destination directory. A check has been in place to check if the operation succeeded or not.

On the first run, a success message is printed. However, succeeding run will fail because the source target will no longer be existing as it has already a new file name as defined by the target file.

Sample Output

Below is the sample output when you run the above example.

java lang File renameTo() example output

Contact Info


Our Goal

JavaTutorialHQ aims to to be The Ultimate Guide on Java with hundreds of examples from basic to advance Topics.

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.