Java - Rename file example

Posted on November 3, 2016


The renameTo() method of the File class is used to rename file. This method returns true if and only if the renaming succeeded; otherwise false.

Here is an example to rename file.

RenameFileExample.java

package com.boraji.tutorial.io;

import java.io.File;

/**
 * @author imssbora
 * RenameFileExample.java
 * Nov 3, 2016
 */
public class RenameFileExample {
	public static void main(String[] args) {
		File file=new File("file.txt");
		File renamedFile=new File("file2.txt");
		
		/*check if both files exist*/
		System.out.println("file.txt exists : "+file.exists());
		System.out.println("file2.txt exists : "+renamedFile.exists());
		
		/*Renaming file*/
		if(file.renameTo(renamedFile)){
			System.out.println("File renamed successfully.");
		}else{
			System.out.println("Failed to rename file.");
		}
		
		/*check again if both files exist*/
		System.out.println("file.txt exists : "+file.exists());
		System.out.println("file2.txt exists : "+renamedFile.exists());
	}
}

Output

file.txt exists : false
file2.txt exists : true
Failed to rename file.
file2.txt exists : true