java.io.File renameTo(File dest)

Description

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.

Throws:

  • 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.

Compatibility

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.

package com.javatutorialhq.java.examples;

import java.io.File;

/*
 * This example source code demonstrates the use of  
 * renameTo() method of File class.
 * 
 */

public class FileRenameToExample {

	public static void main(String[] args) {
		
		// initialize File object
		File origFile = new File("C:javatutorialhqinputtest_file.txt");		
		File destFile = new File("C:javatutorialhqinputtest.txt");
		// check if file exists
		if(origFile.exists()){
			// rename the file
			boolean result = origFile.renameTo(destFile);
			// check if the rename operation is success
			if(result){
				System.out.println("Operation Success");
			}else{
				System.out.println("Operation failed");
			}
			
		}else{
			System.out.println("File does not exist");
		}
	}
}

Sample Output

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

java lang File renameTo() example output